log

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2025 License: Apache-2.0 Imports: 12 Imported by: 8

README

Blueprint Logging System

A structured, context-aware logging system for the Blueprint project that provides consistent logging patterns across different components.

Overview

The Blueprint logging system builds on zerolog to provide:

  • Structured logging with consistent field naming
  • Context propagation for request tracing
  • Component-specific logging (HTTP, Kafka, Database)
  • Performance-optimized logging with minimal allocations
  • Trace and request ID support for distributed systems

Core Components

  • Logger: The main logging interface with methods for each log level
  • Context: Functions for context-aware logging and propagation

Quick Start

// Create a module logger
logger := log.New("myapp")

// Log at different levels
logger.Info("Application started", FV{
    "version": "1.0.0",
})

// Log errors with stack traces
if err := operation(); err != nil {
    logger.Error(err, "Operation failed", log.FV{
        "operation_id": 123,
    })
}

Context-Aware Logging

// Create a context with a logger
ctx, logger := log.NewRequestContext(context.Background(), "api")

// Log using context
log.Info(ctx, "Processing request")

// Pass context to other functions
processItem(ctx, item)

// Extract logger from context
func processItem(ctx context.Context, item Item) {
    logger := log.FromContext(ctx)
    logger.Info("Processing item", log.FV{
        "item_id": item.ID,
    })
}

Configuration

Configure the logging system using:

cfg := log.NewDefaultConfig()
cfg.Level = "info"
cfg.Format = "json"

err := log.Configure(cfg)
if err != nil {
    panic(err)
}

Best Practices

  1. Use context propagation to maintain request context across function calls
  2. Include relevant fields but avoid logging sensitive information
  3. Be consistent with log levels
  4. Use structured logging instead of string concatenation
  5. Properly handle errors and include them in log messages

Complete Documentation

For detailed documentation, see logging.md.

Documentation

Index

Constants

View Source
const (
	// LogContextKey is used to store/retrieve logger from context
	LogContextKey       = "logger"
	LogTraceIDKey       = "trace_id"
	LogModuleKey        = "module"
	LogComponentKey     = "component"
	LogTimestampFormat  = time.RFC3339Nano
	LogCallerSkipFrames = 2

	DefaultLogFile = "application.log"
	LogFmtPretty   = "pretty"
	LogFmtJson     = "json"
)

Configuration constants

Variables

This section is empty.

Functions

func CloseLogFiles

func CloseLogFiles() error

CloseLogFiles close log files

func Configure

func Configure(cfg *Config) error

Configure configures the global logger based on the provided configuration

func Debug

func Debug(ctx context.Context, msg string, fields ...ContextFields)

Debug logs a debug message with the logger from the context

func Debugf

func Debugf(ctx context.Context, msg string, args ...any)

Debugf logs a debug message with the logger from the context

func Error

func Error(ctx context.Context, err error, msg string, fields ...ContextFields)

Error logs an error message with the logger from the context

func Errorf

func Errorf(ctx context.Context, err error, msg string, args ...any)

Errorf logs an error message with the logger from the context

func Fatal

func Fatal(ctx context.Context, err error, msg string, fields ...ContextFields)

Fatal logs a fatal message with the logger from the context

func Fatalf

func Fatalf(ctx context.Context, err error, msg string, args ...any)

Fatalf logs a fatal message with the logger from the context

func Info

func Info(ctx context.Context, msg string, fields ...ContextFields)

Info logs an info message with the logger from the context

func Infof

func Infof(ctx context.Context, msg string, args ...any)

Infof logs an info message with the logger from the context

func NewTraceID

func NewTraceID() string

NewTraceID generates a new trace ID for distributed tracing

func Warn

func Warn(ctx context.Context, msg string, fields ...ContextFields)

Warn logs a warning message with the logger from the context

func Warnf

func Warnf(ctx context.Context, msg string, args ...any)

Warnf logs a warning message with the logger from the context

func WithField

func WithField(ctx context.Context, key string, value interface{}) context.Context

WithField adds a field to the logger in the context and returns the updated context

func WithFields

func WithFields(ctx context.Context, fields ContextFields) context.Context

WithFields adds multiple fields to the logger in the context and returns the updated context

Types

type Config

type Config struct {
	Level            string `json:"level"`
	Format           string `json:"format"` // "pretty" or "json"
	IncludeTimestamp bool   `json:"includeTimestamp"`
	IncludeCaller    bool   `json:"includeCaller"`
	IncludeHostname  bool   `json:"includeHostname"`
	CallerSkipFrames int    `json:"callerSkipFrames"`
	TimeFormat       string `json:"timeFormat"`      // Time format string
	NoColor          bool   `json:"noColor"`         // if true, disable color
	OutputToFile     bool   `json:"outputToFile"`    // Enable file output
	FilePath         string `json:"filePath"`        // Path to log file
	FileAppend       bool   `json:"fileAppend"`      // Append to existing file
	FilePermissions  int    `json:"filePermissions"` // File permissions (e.g., 0644)
	FileFormat       string `json:"fileFormat"`      // file format, "pretty" or json
	FileRotation     bool   `json:"fileRotation"`    // Enable log rotation
	MaxSizeMb        int    `json:"maxSizeMb"`       // Max size in MB before rotation
	MaxBackups       int    `json:"maxBackups"`      // Max number of rotated files to keep
	MaxAgeDays       int    `json:"maxAgeDays"`      // Max age in days to keep rotated files
	Compress         bool   `json:"compress"`        // Compress rotated files
}

Config contains configuration for the logger

func DisableFileAppend

func DisableFileAppend(cfg *Config) *Config

DisableFileAppend disables appending to existing log files (will overwrite)

func EnableFileOutput

func EnableFileOutput(cfg *Config, filePath string) *Config

EnableFileOutput enables file logging with the given file path

func NewDefaultConfig

func NewDefaultConfig() *Config

NewDefaultConfig returns a default logging configuration

func SetFileFormat

func SetFileFormat(cfg *Config, format string) *Config

SetFileFormat sets the output format for file logging

func (*Config) Validate

func (c *Config) Validate() error

Validate validate log configuration

type ContextFields

type ContextFields map[string]interface{}

ContextFields is a map of fields to add to log messages

func MergeContextFields

func MergeContextFields(fieldSets ...ContextFields) ContextFields

MergeContextFields merges multiple context fields maps into a single map

type KV

type KV map[string]interface{}

KV is a helper to field map

type Logger

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

Logger wraps zerolog.Logger to provide consistent logging patterns

func ExtractLoggerFromContext

func ExtractLoggerFromContext(ctx context.Context) *Logger

ExtractLoggerFromContext extracts a logger from the given context If no logger is found, a new default logger is created

func FromContext

func FromContext(ctx context.Context) *Logger

FromContext retrieves a logger from the context If no logger is found, a new default logger is returned

func New

func New(module string) *Logger

New creates a new logger with module information

func NewRequestContext

func NewRequestContext(parentCtx context.Context, moduleName string) (context.Context, *Logger)

NewRequestContext creates a new context with a logger that has a trace ID This is useful for tracking requests through multiple services

func NewWithComponent

func NewWithComponent(module, component string) *Logger

NewWithComponent creates a new logger with module and component information

func (*Logger) Debug

func (l *Logger) Debug(msg string, fields ...map[string]interface{})

Debug logs a debug message with the given fields

func (*Logger) Debugf

func (l *Logger) Debugf(msg string, fields ...any)

Debugf logs a debug message with the given fields

func (*Logger) Error

func (l *Logger) Error(err error, msg string, fields ...map[string]interface{})

Error logs an error message with the given fields It automatically adds stack information

func (*Logger) Errorf

func (l *Logger) Errorf(err error, msg string, fields ...any)

Errorf logs an error message with the given fields It automatically adds stack information

func (*Logger) Fatal

func (l *Logger) Fatal(err error, msg string, fields ...map[string]interface{})

Fatal logs a fatal message with the given fields and exits the application

func (*Logger) Fatalf

func (l *Logger) Fatalf(err error, msg string, fields ...any)

Fatalf logs a fatal message with the given fields and exits the application

func (*Logger) GetTraceID

func (l *Logger) GetTraceID() string

GetTraceID returns the trace ID associated with this logger

func (*Logger) GetZerolog

func (l *Logger) GetZerolog() zerolog.Logger

GetZerolog returns the underlying zerolog.Logger

func (*Logger) Hostname

func (l *Logger) Hostname() string

Hostname get configured hostname

func (*Logger) Info

func (l *Logger) Info(msg string, fields ...map[string]interface{})

Info logs an info message with the given fields

func (*Logger) Infof

func (l *Logger) Infof(msg string, fields ...any)

Infof logs an info message with the given fields

func (*Logger) ModuleInfo

func (l *Logger) ModuleInfo() string

ModuleInfo get module name

func (*Logger) Warn

func (l *Logger) Warn(msg string, fields ...map[string]interface{})

Warn logs a warning message with the given fields

func (*Logger) Warnf

func (l *Logger) Warnf(msg string, fields ...any)

Warnf logs a warning message with the given fields

func (*Logger) WithContext

func (l *Logger) WithContext(ctx context.Context) context.Context

WithContext adds the logger to the context

func (*Logger) WithField

func (l *Logger) WithField(key string, value interface{}) *Logger

WithField adds a field to the logger

func (*Logger) WithOutput

func (l *Logger) WithOutput(output io.Writer) *Logger

WithOutput use a custom output

func (*Logger) WithTraceID

func (l *Logger) WithTraceID(traceID string) *Logger

WithTraceID creates a new logger with the specified trace ID

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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