logging

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2025 License: MIT Imports: 5 Imported by: 0

README

Logging Package

The logging package provides structured logging with Zap for high-performance logging in Go applications. It wraps the zap logging library and adds features like trace ID extraction from context and context-aware logging methods.

Features

  • Log Levels: Debug, Info, Warn, Error, Fatal
  • Structured Logging: Key-value pairs for better searchability
  • Output Formats: JSON, console
  • Context-Aware Logging: Log with context information including trace IDs
  • Performance: High-performance logging with minimal allocations
  • Trace Integration: Automatic extraction of trace IDs from OpenTelemetry context

Installation

go get github.com/abitofhelp/servicelib/logging

Usage

Basic Usage
package main

import (
    "github.com/abitofhelp/servicelib/logging"
)

func main() {
    // Create a new logger
    logger, err := logging.NewLogger("info", true)
    if err != nil {
        panic("Failed to create logger: " + err.Error())
    }
    defer logger.Sync()

    // Log messages
    logger.Info("Starting application", zap.String("version", "1.0.0"))
    logger.Debug("Debug information")
    logger.Warn("Warning message", zap.Int("code", 123))
    logger.Error("Error occurred", zap.Error(errors.New("sample error")))
}
Context-Aware Logging
package main

import (
    "context"
    "github.com/abitofhelp/servicelib/logging"
    "go.uber.org/zap"
)

func main() {
    // Create a base logger
    baseLogger, _ := logging.NewLogger("info", true)
    
    // Create a context logger
    contextLogger := logging.NewContextLogger(baseLogger)
    
    // Create a context
    ctx := context.Background()
    
    // Log with context
    contextLogger.Info(ctx, "Processing request", zap.String("requestID", "123456"))
    
    // In a function with trace context
    processRequest(ctx, contextLogger)
}

func processRequest(ctx context.Context, logger *logging.ContextLogger) {
    // The trace ID from the context will be automatically included in the log
    logger.Info(ctx, "Processing data", zap.Int("items", 42))
    
    if err := doSomething(); err != nil {
        logger.Error(ctx, "Failed to process data", zap.Error(err))
    }
}
Adding Trace IDs to Logs
package main

import (
    "context"
    "github.com/abitofhelp/servicelib/logging"
    "go.opentelemetry.io/otel"
    "go.uber.org/zap"
)

func main() {
    // Create a base logger
    baseLogger, _ := logging.NewLogger("info", false)
    
    // Create a context with trace
    ctx, span := otel.Tracer("example").Start(context.Background(), "operation")
    defer span.End()
    
    // Add trace ID to logger
    loggerWithTrace := logging.WithTraceID(ctx, baseLogger)
    
    // Log with trace ID
    loggerWithTrace.Info("This log includes trace ID")
}

Configuration

The logger can be configured with different log levels and output formats:

// Development mode (console output with colors)
logger, err := logging.NewLogger("debug", true)

// Production mode (JSON output)
logger, err := logging.NewLogger("info", false)

Available log levels:

  • debug: Detailed information for debugging
  • info: General operational information
  • warn: Warning events that might cause issues
  • error: Error events that might still allow the application to continue
  • fatal: Severe error events that cause the application to terminate

Best Practices

  1. Use Structured Logging: Always use structured logging with key-value pairs instead of string formatting.

    // Good
    logger.Info("User logged in", zap.String("username", user.Name), zap.String("ip", ip))
    
    // Avoid
    logger.Info(fmt.Sprintf("User %s logged in from %s", user.Name, ip))
    
  2. Include Context: Always pass context to logging methods when available to include trace information.

  3. Log Levels: Use appropriate log levels for different types of information.

  4. Error Logging: When logging errors, always include the error object using zap.Error(err).

  5. Performance: In hot paths, check if the log level is enabled before constructing expensive log messages.

    if logger.Core().Enabled(zapcore.DebugLevel) {
        logger.Debug("Expensive debug info", zap.Any("data", generateExpensiveDebugData()))
    }
    

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package logging provides centralized logging functionality for the family service. It wraps the zap logging library and adds features like trace ID extraction from context and context-aware logging methods. This package is part of the infrastructure layer and provides logging capabilities to all other layers of the application.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewLogger

func NewLogger(level string, development bool) (*zap.Logger, error)

NewLogger creates a new zap logger configured based on the provided level and environment. It sets up appropriate encoders and log levels for either development or production use. Parameters:

  • level: The minimum log level as a string (e.g., "debug", "info", "warn", "error")
  • development: Whether to use development mode with console output (true) or production mode with JSON output (false)

Returns:

  • *zap.Logger: A configured zap logger instance
  • error: An error if logger creation fails

func WithTraceID

func WithTraceID(ctx context.Context, logger *zap.Logger) *zap.Logger

WithTraceID adds trace ID and span ID to the logger from the provided context. This enables correlation between logs and traces for distributed tracing. Parameters:

  • ctx: The context containing trace information
  • logger: The base logger to enhance with trace information

Returns:

  • *zap.Logger: A new logger with trace ID and span ID fields added if available

Types

type ContextLogger

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

ContextLogger is a logger that includes context information in log entries. It wraps a zap.Logger and provides methods that accept a context parameter, automatically extracting and including trace information in log entries.

func NewContextLogger

func NewContextLogger(base *zap.Logger) *ContextLogger

NewContextLogger creates a new context-aware logger wrapping the provided base logger. If base is nil, a no-op logger will be used to prevent nil pointer panics. Parameters:

  • base: The base zap logger to wrap

Returns:

  • *ContextLogger: A new context logger instance

func (*ContextLogger) Debug

func (l *ContextLogger) Debug(ctx context.Context, msg string, fields ...zap.Field)

Debug logs a debug-level message with context information. Parameters:

  • ctx: The context containing trace information
  • msg: The message to log
  • fields: Additional fields to include in the log entry

func (*ContextLogger) Error

func (l *ContextLogger) Error(ctx context.Context, msg string, fields ...zap.Field)

Error logs an error-level message with context information. Parameters:

  • ctx: The context containing trace information
  • msg: The message to log
  • fields: Additional fields to include in the log entry

func (*ContextLogger) Fatal

func (l *ContextLogger) Fatal(ctx context.Context, msg string, fields ...zap.Field)

Fatal logs a fatal-level message with context information. This will terminate the program after logging the message. Parameters:

  • ctx: The context containing trace information
  • msg: The message to log
  • fields: Additional fields to include in the log entry

func (*ContextLogger) Info

func (l *ContextLogger) Info(ctx context.Context, msg string, fields ...zap.Field)

Info logs an info-level message with context information. Parameters:

  • ctx: The context containing trace information
  • msg: The message to log
  • fields: Additional fields to include in the log entry

func (*ContextLogger) Sync

func (l *ContextLogger) Sync() error

Sync flushes any buffered log entries to their destination. This should be called before program termination to ensure all logs are written. Returns:

  • error: An error if flushing fails

func (*ContextLogger) Warn

func (l *ContextLogger) Warn(ctx context.Context, msg string, fields ...zap.Field)

Warn logs a warning-level message with context information. Parameters:

  • ctx: The context containing trace information
  • msg: The message to log
  • fields: Additional fields to include in the log entry

func (*ContextLogger) With

func (l *ContextLogger) With(ctx context.Context) *zap.Logger

With returns a logger with trace information from the given context. Parameters:

  • ctx: The context containing trace information

Returns:

  • *zap.Logger: A logger with trace ID and span ID fields added if available

type Logger

type Logger interface {
	// Debug logs a debug-level message with context information
	Debug(ctx context.Context, msg string, fields ...zap.Field)

	// Info logs an info-level message with context information
	Info(ctx context.Context, msg string, fields ...zap.Field)

	// Warn logs a warning-level message with context information
	Warn(ctx context.Context, msg string, fields ...zap.Field)

	// Error logs an error-level message with context information
	Error(ctx context.Context, msg string, fields ...zap.Field)

	// Fatal logs a fatal-level message with context information
	Fatal(ctx context.Context, msg string, fields ...zap.Field)

	// Sync flushes any buffered log entries
	Sync() error
}

Logger defines the interface for context-aware logging

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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