logger

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2025 License: MIT Imports: 7 Imported by: 0

README

Go Reference Go CI

🚀 High-Performance Structured Logger for Go: The logger Package

The logger package is a high-performance, simple, and opinionated solution for structured logging in Go. Designed as a standalone utility to unify logging practices, it ensures your logs are both human-readable and easily parsable by analysis systems (e.g., Elastic Stack, Grafana Loki).

✨ Key Features

  1. Exceptional Performance: Built for minimal overhead and high write speed, which is critical for demanding production environments.

  2. Unified Interface: Always use the dedicated Message and Json structs for all log levels, eliminating confusion and standardizing code across your application.

  3. Level Control: Easily configure the minimum logging level (level.Level) during initialization to precisely control log volume.

  4. Structured Data (JSON-Ready): Additional context fields are always recorded in key-value format (Json), making your logs instantly ready for centralized analysis.

  5. Contextual Logging: Use the With() method to create child loggers with permanent, attached fields (e.g., request_id, service name) for easier tracing.

🛠️ Installation

Get the package using the standard go get command:

go get github.com/FullTOPik/logger

Note: The level package is now part of this module and will be installed automatically.

🚀 Quick Start

1. Initializing the Logger

When creating the logger, you must specify the minimum logging level (level.Level), imported from the /level sub-package. Logs below this threshold will be ignored.

package main

import (
    "github.com/FullTOPik/logger"
    "github.com/FullTOPik/logger/level" 
    "time"
)

func main() {
    // 1. Initialization. Sets the minimum level to "Warn".
    // Info and Debug logs will be ignored.
    log := logger.NewLogger(level.Warn)
    
    // 2. Mandatory call! Ensures buffer flush before the application exits.
    defer log.Close() 

	// Create a contextual logger for a specific request or session.
	// All logs made using requestLogger will automatically include request_id.
	requestLogger := log.With(logger.Json{
		"service":    "PaymentService",
		"request_id": "req-a1b2c3d4",
	})

    // --- Usage Example ---

    // 🔴 This log will be recorded
    requestLogger.Warn(
        logger.Message{
            StrFormat: "Slow operation detected on service %s (T=%dms)",
            Args:      logger.MessageArgs("PaymentsGateway", 500),
        },
        logger.Json{
            "user_id": "u4321",
            "time_start": time.Now().Format(time.RFC3339),
        },
    )

    // 🟢 This log will be ignored (the "Warn" level ignores "Info")
    requestLogger.Info(
        logger.Message{StrFormat: "Starting request processing"},
        nil, // nil can be passed if no additional context data is required
    )
}
2. Data Types

To ensure logging consistency, you always work with two custom data types:

Type Purpose Description
Message Formatted String Used to create the human-readable log entry. Contains StrFormat (a fmt.Sprintf style format string) and Args (its arguments).
Json Structured Data The map[string]string type for passing all custom context fields (request ID, tags, status codes). These are written to the log as separate JSON fields.

💡 API Reference

The Logger Interface

Your logger implements the following simple interface:

type Logger interface {
    Info(Message, Json)
    Error(Message, Json)
    Warn(Message, Json)
    Debug(Message, Json)
    Close()

    With(Json) Logger // Added for contextual logging
}
Method Level Description
Info(msg, data) Info General information about execution flow (e.g., function start, successful connection).
Error(msg, data) Error Records critical errors requiring immediate intervention.
Warn(msg, data) Warn Warnings about potential issues or undesirable behavior.
Debug(msg, data) Debug Detailed technical information, useful only for debugging.
With(fields)) N/A Returns a new Logger instance with the provided key-value fields permanently attached to all subsequent log calls.
Close() N/A Mandatory! Flushes internal buffers and shuts down the logger gracefully.

🌐 Open Source & Licensing

Community contributions are welcome. The code is distributed under the MIT License license.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MessageArgs

func MessageArgs(args ...any) []any

MessageArgs is a helper function for convenience.

Types

type DefaultLogger added in v1.0.2

type DefaultLogger struct {
	// contains filtered or unexported fields
}

DefaultLogger is the concrete implementation of the Logger interface, wrapping zap.SugaredLogger. This structure is exported to satisfy GoDoc requirements, but NewLogger returns the Logger interface.

func (*DefaultLogger) Close added in v1.0.2

func (l *DefaultLogger) Close()

Close flushes any buffered log entries. Mandatory to call with defer.

func (*DefaultLogger) Debug added in v1.0.2

func (l *DefaultLogger) Debug(msg Message, data Json)

Debug logs a message at Debug level.

func (*DefaultLogger) Error added in v1.0.2

func (l *DefaultLogger) Error(msg Message, data Json)

Error logs a message at Error level.

func (*DefaultLogger) Info added in v1.0.2

func (l *DefaultLogger) Info(msg Message, data Json)

Info logs a message at Info level.

func (*DefaultLogger) Warn added in v1.0.2

func (l *DefaultLogger) Warn(msg Message, data Json)

Warn logs a message at Warn level.

func (*DefaultLogger) With added in v1.0.2

func (l *DefaultLogger) With(fields Json) Logger

With returns a new Logger with the provided fields permanently attached to all subsequent log calls.

type Json

type Json map[string]any

Json is used for structured key-value context data.

type Logger

type Logger interface {
	Info(Message, Json)
	Error(Message, Json)
	Warn(Message, Json)
	Debug(Message, Json)
	// Close flushes any buffered log entries. Mandatory to call with defer.
	Close()
	// With returns a new Logger with fields permanently attached.
	With(fields Json) Logger
}

Logger interface defines the public methods for logging. It is the primary type applications interact with.

func NewLogger

func NewLogger(minLevel level.Level) Logger

NewLogger initializes and returns a new Logger instance, set to the given minimum log level.

It sets up a JSON encoder suitable for production use (log aggregation systems). You must call Close() via defer immediately after initialization.

Example:

log := NewLogger(level.Info)
defer log.Close()

type Message

type Message struct {
	StrFormat string
	Args      []any
}

Message is used for the human-readable part of the log, supporting fmt.Sprintf syntax.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL