logging

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2025 License: MIT Imports: 6 Imported by: 0

README

Logging

Overview

The Logging component provides a structured logging solution for your services. It offers a consistent API for logging messages with different severity levels, structured context, and integration with popular logging backends.

Features

  • Structured Logging: Log messages with structured context
  • Multiple Severity Levels: Debug, Info, Warn, Error, Fatal
  • Context Integration: Propagate context values to log entries
  • Trace ID Support: Automatically include trace IDs in log entries
  • Multiple Backends: Support for multiple logging backends

Installation

go get github.com/abitofhelp/servicelib/logging

Quick Start

See the Basic Usage example for a complete, runnable example of how to use the logging component.

Configuration

See the Context Aware Logging example for a complete, runnable example of how to configure the logging component.

API Documentation

Core Types

The logging component provides several core types for logging.

Logger

The main interface for logging.

type Logger interface {
    // Methods
}
Entry

Represents a log entry.

type Entry struct {
    // Fields
}
Key Methods

The logging component provides several key methods for logging.

Debug

Logs a message at the Debug level.

func (l *Logger) Debug(ctx context.Context, msg string, fields ...Field)
Info

Logs a message at the Info level.

func (l *Logger) Info(ctx context.Context, msg string, fields ...Field)
Warn

Logs a message at the Warn level.

func (l *Logger) Warn(ctx context.Context, msg string, fields ...Field)
Error

Logs a message at the Error level.

func (l *Logger) Error(ctx context.Context, msg string, fields ...Field)
Fatal

Logs a message at the Fatal level and then calls os.Exit(1).

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

Examples

For complete, runnable examples, see the following directories in the EXAMPLES directory:

Best Practices

  1. Use Structured Logging: Always use structured logging for better searchability
  2. Include Context: Always include context in log calls
  3. Use Appropriate Levels: Use appropriate log levels for different types of messages
  4. Include Trace IDs: Include trace IDs in log entries for distributed tracing
  5. Handle Errors: Log errors with appropriate context

Troubleshooting

Common Issues
Missing Context Values

If context values are not appearing in log entries, ensure that you're using the correct context and that the values are set correctly.

Performance Issues

If you're experiencing performance issues with logging, consider reducing the log level or batching log entries.

  • Context - Context utilities for logging
  • Telemetry - Telemetry integration for logging

Contributing

Contributions to this component are welcome! Please see the Contributing Guide for more information.

License

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

Documentation

Overview

Package logging provides centralized logging functionality for services.

This package wraps the zap logging library and adds features like trace ID extraction from context and context-aware logging methods. It is designed to be used throughout the application to provide consistent, structured logging with proper context information.

Key features:

  • Context-aware logging with automatic trace ID extraction
  • Support for different log levels (Debug, Info, Warn, Error, Fatal)
  • Configurable for both development (console output) and production (JSON output) environments
  • Integration with OpenTelemetry for distributed tracing
  • Structured logging with additional fields

The package provides two main components:

  • ContextLogger: A wrapper around zap.Logger that automatically extracts trace information from context and includes it in log entries
  • Logger interface: An abstraction that can be implemented by different logging backends

Example usage:

// Create a new logger
zapLogger, err := logging.NewLogger("info", true)
if err != nil {
    panic(err)
}
defer zapLogger.Sync()

// Create a context logger
logger := logging.NewContextLogger(zapLogger)

// Log with context
ctx := context.Background()
logger.Info(ctx, "Application started", zap.String("app_name", "example"))

// Log an error
if err := someOperation(); err != nil {
    logger.Error(ctx, "Operation failed", zap.Error(err))
}

The package is designed to be used as a dependency by other packages in the application, providing a consistent logging interface throughout the codebase.

Package logging provides centralized logging functionality for services.

Package logging provides centralized logging functionality for services. 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 = interfaces.Logger

Logger is an alias for interfaces.Logger for backward compatibility

Directories

Path Synopsis
Package interfaces defines the interfaces for the logging package.
Package interfaces defines the interfaces for the logging package.
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