Documentation
¶
Index ¶
- Constants
- Variables
- func ConditionalLog(condition bool, logger Logger, level string, msg string, fields ...Field)
- func FieldMap(fields []Field) map[string]interface{}
- func FieldsToZap(fields []Field) []zap.Field
- func LogPanic(logger Logger, recovered interface{})
- func LogPanicWithFields(logger Logger, recovered interface{}, fields ...Field)
- func Must(err error, logger Logger, msg string, fields ...Field)
- func MustNotNil(value interface{}, logger Logger, msg string, fields ...Field)
- func RequestIDFromContext(ctx context.Context) string
- func SetGlobalLogger(l Logger)
- func TraceIDFromContext(ctx context.Context) string
- func Track(ctx context.Context, name string) func()
- func TrackWithFields(ctx context.Context, name string, fields ...Field) func()
- func TrackWithLogger(logger Logger, name string) func()
- func UserIDFromContext(ctx context.Context) string
- func ValidateField(field Field) error
- func WithLogger(ctx context.Context, logger Logger) context.Context
- func WithRequestID(ctx context.Context, requestID string) context.Context
- func WithTraceID(ctx context.Context, traceID string) context.Context
- func WithUserID(ctx context.Context, userID string) context.Context
- type ColorScheme
- type ColoredWriteSyncer
- type CustomField
- type ErrorHandler
- type Field
- type FieldGroup
- type LazyField
- type LogEntry
- type LogLevel
- type Logger
- func DatabaseQueryLogger(logger Logger, query, table string, rows int64, duration time.Duration) Logger
- func GetGlobalLogger() Logger
- func HTTPRequestLogger(logger Logger, method, path, userAgent string, status int) Logger
- func LoggerFromContext(ctx context.Context) Logger
- func NewDevelopmentLogger() Logger
- func NewDevelopmentLoggerWithLevel(level zapcore.Level) Logger
- func NewLogger(config LoggingConfig) Logger
- func NewNoopLogger() Logger
- func NewProductionLogger() Logger
- func NewTestLogger() Logger
- func ServiceLogger(logger Logger, name, version, environment string) Logger
- type LoggingConfig
- type LoggingWriter
- type PerformanceMonitor
- type StructuredLog
- func (sl *StructuredLog) Debug(msg string)
- func (sl *StructuredLog) Error(msg string)
- func (sl *StructuredLog) Fatal(msg string)
- func (sl *StructuredLog) Info(msg string)
- func (sl *StructuredLog) Logger() Logger
- func (sl *StructuredLog) Warn(msg string)
- func (sl *StructuredLog) WithContext(ctx context.Context) *StructuredLog
- func (sl *StructuredLog) WithDatabaseQuery(query, table string, rows int64, duration time.Duration) *StructuredLog
- func (sl *StructuredLog) WithField(field Field) *StructuredLog
- func (sl *StructuredLog) WithFields(fields ...Field) *StructuredLog
- func (sl *StructuredLog) WithGroup(group *FieldGroup) *StructuredLog
- func (sl *StructuredLog) WithHTTPRequest(method, path, userAgent string, status int) *StructuredLog
- func (sl *StructuredLog) WithService(name, version, environment string) *StructuredLog
- type SugarLogger
- type TestLogger
- func (tl *TestLogger) AssertHasLog(level, message string) bool
- func (tl *TestLogger) Clear()
- func (tl *TestLogger) CountLogs(level string) int
- func (tl *TestLogger) Debug(msg string, fields ...Field)
- func (tl *TestLogger) Debugf(template string, args ...interface{})
- func (tl *TestLogger) Error(msg string, fields ...Field)
- func (tl *TestLogger) Errorf(template string, args ...interface{})
- func (tl *TestLogger) Fatal(msg string, fields ...Field)
- func (tl *TestLogger) Fatalf(template string, args ...interface{})
- func (tl *TestLogger) GetLogs() []LogEntry
- func (tl *TestLogger) GetLogsByLevel(level string) []LogEntry
- func (tl *TestLogger) Info(msg string, fields ...Field)
- func (tl *TestLogger) Infof(template string, args ...interface{})
- func (tl *TestLogger) Named(name string) Logger
- func (tl *TestLogger) Sugar() SugarLogger
- func (tl *TestLogger) Sync() error
- func (tl *TestLogger) Warn(msg string, fields ...Field)
- func (tl *TestLogger) Warnf(template string, args ...interface{})
- func (tl *TestLogger) With(fields ...Field) Logger
- func (tl *TestLogger) WithContext(ctx context.Context) Logger
- type ZapField
Constants ¶
const ( // Reset and basic colors Reset = "\033[0m" // Text styles Bold = "\033[1m" Dim = "\033[2m" Italic = "\033[3m" Underline = "\033[4m" // Foreground colors Black = "\033[30m" Red = "\033[31m" Green = "\033[32m" Yellow = "\033[33m" Blue = "\033[34m" Magenta = "\033[35m" Cyan = "\033[36m" White = "\033[37m" // Bright foreground colors BrightBlack = "\033[90m" BrightRed = "\033[91m" BrightGreen = "\033[92m" BrightYellow = "\033[93m" BrightBlue = "\033[94m" BrightMagenta = "\033[95m" BrightCyan = "\033[96m" BrightWhite = "\033[97m" // Background colors BgBlack = "\033[40m" BgRed = "\033[41m" BgGreen = "\033[42m" BgYellow = "\033[43m" BgBlue = "\033[44m" BgMagenta = "\033[45m" BgCyan = "\033[46m" BgWhite = "\033[47m" )
Extended ANSI color codes and styles
Variables ¶
var ( // Basic type constructors String = func(key, val string) Field { return ZapField{zap.String(key, val)} } Int = func(key string, val int) Field { return ZapField{zap.Int(key, val)} } Int8 = func(key string, val int8) Field { return ZapField{zap.Int8(key, val)} } Int16 = func(key string, val int16) Field { return ZapField{zap.Int16(key, val)} } Int32 = func(key string, val int32) Field { return ZapField{zap.Int32(key, val)} } Int64 = func(key string, val int64) Field { return ZapField{zap.Int64(key, val)} } Uint = func(key string, val uint) Field { return ZapField{zap.Uint(key, val)} } Uint8 = func(key string, val uint8) Field { return ZapField{zap.Uint8(key, val)} } Uint16 = func(key string, val uint16) Field { return ZapField{zap.Uint16(key, val)} } Uint32 = func(key string, val uint32) Field { return ZapField{zap.Uint32(key, val)} } Uint64 = func(key string, val uint64) Field { return ZapField{zap.Uint64(key, val)} } Float32 = func(key string, val float32) Field { return ZapField{zap.Float32(key, val)} } Float64 = func(key string, val float64) Field { return ZapField{zap.Float64(key, val)} } Bool = func(key string, val bool) Field { return ZapField{zap.Bool(key, val)} } // Time and duration constructors Time = func(key string, val time.Time) Field { return ZapField{zap.Time(key, val)} } Duration = func(key string, val time.Duration) Field { return ZapField{zap.Duration(key, val)} } // Error constructor Error = func(err error) Field { return ZapField{zap.Error(err)} } // Advanced constructors Stringer = func(key string, val fmt.Stringer) Field { return ZapField{zap.Stringer(key, val)} } Any = func(key string, val interface{}) Field { return ZapField{zap.Any(key, val)} } Namespace = func(key string) Field { return ZapField{zap.Namespace(key)} } Binary = func(key string, val []byte) Field { return ZapField{zap.Binary(key, val)} } ByteString = func(key string, val []byte) Field { return ZapField{zap.ByteString(key, val)} } Reflect = func(key string, val interface{}) Field { return ZapField{zap.Reflect(key, val)} } Complex64 = func(key string, val complex64) Field { return ZapField{zap.Complex64(key, val)} } Complex128 = func(key string, val complex128) Field { return ZapField{zap.Complex128(key, val)} } Object = func(key string, val zapcore.ObjectMarshaler) Field { return ZapField{zap.Object(key, val)} } Array = func(key string, val zapcore.ArrayMarshaler) Field { return ZapField{zap.Array(key, val)} } Stack = func(key string) Field { return ZapField{zap.Stack(key)} } Strings = func(key string, val []string) Field { return ZapField{zap.Strings(key, val)} } )
Enhanced field constructors that return wrapped fields
var ( // HTTP-related fields HTTPMethod = func(method string) Field { return String("http.method", method) } HTTPStatus = func(status int) Field { return Int("http.status", status) } HTTPPath = func(path string) Field { return String("http.path", path) } HTTPURL = func(url *url.URL) Field { if url == nil { return String("http.url", "") } return String("http.url", url.String()) } HTTPUserAgent = func(userAgent string) Field { return String("http.user_agent", userAgent) } // Database-related fields DatabaseQuery = func(query string) Field { return String("db.query", query) } DatabaseTable = func(table string) Field { return String("db.table", table) } DatabaseRows = func(rows int64) Field { return Int64("db.rows", rows) } // Service-related fields ServiceName = func(name string) Field { return String("service.name", name) } ServiceVersion = func(version string) Field { return String("service.version", version) } ServiceEnvironment = func(env string) Field { return String("service.environment", env) } // Performance-related fields LatencyMs = func(latency time.Duration) Field { return Float64("latency.ms", float64(latency.Nanoseconds())/1e6) } MemoryUsage = func(bytes int64) Field { return Int64("memory.usage", bytes) } // Custom field constructors Custom = func(key string, value interface{}) Field { return CustomField{key: key, value: value} } Lazy = func(key string, valueFunc func() interface{}) Field { return LazyField{key: key, valueFunc: valueFunc} } // Conditional field - only adds field if condition is true Conditional = func(condition bool, key string, value interface{}) Field { if condition { return Custom(key, value) } return nil } // Nullable field - only adds field if value is not nil Nullable = func(key string, value interface{}) Field { if value != nil { return Custom(key, value) } return nil } )
Additional utility field constructors
var ( // Request context fields RequestID = func(ctx context.Context) Field { if id := RequestIDFromContext(ctx); id != "" { return String("request_id", id) } return nil } TraceID = func(ctx context.Context) Field { if id := TraceIDFromContext(ctx); id != "" { return String("trace_id", id) } return nil } UserID = func(ctx context.Context) Field { if id := UserIDFromContext(ctx); id != "" { return String("user_id", id) } return nil } // Combined context fields ContextFields = func(ctx context.Context) []Field { var fields []Field if id := RequestIDFromContext(ctx); id != "" { fields = append(fields, String("request_id", id)) } if id := TraceIDFromContext(ctx); id != "" { fields = append(fields, String("trace_id", id)) } if id := UserIDFromContext(ctx); id != "" { fields = append(fields, String("user_id", id)) } return fields } )
Context-aware field constructors
var ( // HTTPRequestGroup creates a group of HTTP request fields HTTPRequestGroup = func(method, path, userAgent string, status int) *FieldGroup { return NewFieldGroup( HTTPMethod(method), HTTPPath(path), HTTPUserAgent(userAgent), HTTPStatus(status), ) } // DatabaseQueryGroup creates a group of database query fields DatabaseQueryGroup = func(query, table string, rows int64, duration time.Duration) *FieldGroup { return NewFieldGroup( DatabaseQuery(query), DatabaseTable(table), DatabaseRows(rows), Duration("query_duration", duration), ) } // ServiceInfoGroup creates a group of service information fields ServiceInfoGroup = func(name, version, environment string) *FieldGroup { return NewFieldGroup( ServiceName(name), ServiceVersion(version), ServiceEnvironment(environment), ) } )
Predefined field groups
var ( DebugColors = ColorScheme{ Level: Dim + Cyan, Timestamp: Dim + BrightBlack, Message: Cyan, Fields: Dim + Cyan, Key: BrightCyan, Value: Cyan, } InfoColors = ColorScheme{ Level: Bold + Green, Timestamp: Dim + BrightBlack, Message: White, Fields: Green, Key: BrightGreen, Value: Green, } WarnColors = ColorScheme{ Level: Bold + Yellow, Timestamp: Dim + BrightBlack, Message: Yellow, Fields: Yellow, Key: BrightYellow, Value: Yellow, } ErrorColors = ColorScheme{ Level: Bold + Red, Timestamp: Dim + BrightBlack, Message: BrightRed, Fields: Red, Key: BrightRed, Value: Red, } FatalColors = ColorScheme{ Level: Bold + BgRed + White, Timestamp: Dim + BrightBlack, Message: Bold + Magenta, Fields: Magenta, Key: BrightMagenta, Value: Magenta, } )
Log level color schemes
Functions ¶
func ConditionalLog ¶
ConditionalLog logs only if condition is true
func FieldsToZap ¶
FieldsToZap converts Field interfaces to zap.Field efficiently
func LogPanic ¶
func LogPanic(logger Logger, recovered interface{})
LogPanic logs a panic with stack trace
func LogPanicWithFields ¶
LogPanicWithFields logs a panic with additional fields
func MustNotNil ¶
MustNotNil logs fatally if value is nil
func RequestIDFromContext ¶
RequestIDFromContext extracts the request ID from the context
func SetGlobalLogger ¶
func SetGlobalLogger(l Logger)
SetGlobalLogger sets the global logger instance
func TraceIDFromContext ¶
TraceIDFromContext extracts the trace ID from the context
func TrackWithFields ¶
TrackWithFields logs the execution time with additional fields
func TrackWithLogger ¶
TrackWithLogger logs the execution time using a specific logger
func UserIDFromContext ¶
UserIDFromContext extracts the user ID from the context
func ValidateField ¶
ValidateField validates a field and returns an error if invalid
func WithLogger ¶
WithLogger adds a logger to the context
func WithRequestID ¶
WithRequestID adds a request ID to the context
func WithTraceID ¶
WithTraceID adds a trace ID to the context
Types ¶
type ColorScheme ¶
type ColorScheme struct {
Level string
Timestamp string
Message string
Fields string
Key string
Value string
}
ColorScheme defines colors for different log components
type ColoredWriteSyncer ¶
type ColoredWriteSyncer struct {
zapcore.WriteSyncer
}
ColoredWriteSyncer wraps WriteSyncer to add full-line coloring and fix spacing
type CustomField ¶
type CustomField struct {
// contains filtered or unexported fields
}
CustomField represents a field with custom key-value pairs
func (CustomField) ZapField ¶
func (f CustomField) ZapField() zap.Field
ZapField converts to zap.Field
type ErrorHandler ¶
type ErrorHandler struct {
// contains filtered or unexported fields
}
ErrorHandler provides a callback-based error handler with logging
func NewErrorHandler ¶
func NewErrorHandler(logger Logger, callback func(error)) *ErrorHandler
NewErrorHandler creates a new error handler
func (*ErrorHandler) Handle ¶
func (eh *ErrorHandler) Handle(err error, msg string, fields ...Field)
Handle handles an error by logging it and calling the callback
func (*ErrorHandler) HandleWithLevel ¶
func (eh *ErrorHandler) HandleWithLevel(err error, level string, msg string, fields ...Field)
HandleWithLevel handles an error at a specific log level
type Field ¶
type Field interface {
Key() string
Value() interface{}
// ZapField returns the underlying zap.Field for efficient conversion
ZapField() zap.Field
}
Field represents a structured log field
func MergeFields ¶
MergeFields merges multiple field slices into one
func SanitizeFields ¶
SanitizeFields removes nil and invalid fields
func WrapZapField ¶
WrapZapField wraps a zap.Field to implement the Field interface
func WrapZapFields ¶
WrapZapFields wraps multiple zap.Fields
type FieldGroup ¶
type FieldGroup struct {
// contains filtered or unexported fields
}
FieldGroup represents a group of related fields
func NewFieldGroup ¶
func NewFieldGroup(fields ...Field) *FieldGroup
NewFieldGroup creates a new field group
func (*FieldGroup) Add ¶
func (fg *FieldGroup) Add(fields ...Field) *FieldGroup
Add adds fields to the group
func (*FieldGroup) Fields ¶
func (fg *FieldGroup) Fields() []Field
Fields returns all fields in the group
func (*FieldGroup) ZapFields ¶
func (fg *FieldGroup) ZapFields() []zap.Field
ZapFields converts all fields to zap.Fields
type LazyField ¶
type LazyField struct {
// contains filtered or unexported fields
}
LazyField represents a field that evaluates its value lazily
type Logger ¶
type Logger interface {
// Logging levels
Debug(msg string, fields ...Field)
Info(msg string, fields ...Field)
Warn(msg string, fields ...Field)
Error(msg string, fields ...Field)
Fatal(msg string, fields ...Field)
// Formatted logging
Debugf(template string, args ...interface{})
Infof(template string, args ...interface{})
Warnf(template string, args ...interface{})
Errorf(template string, args ...interface{})
Fatalf(template string, args ...interface{})
// Context and enrichment
With(fields ...Field) Logger
WithContext(ctx context.Context) Logger
Named(name string) Logger
// Sugar logger
Sugar() SugarLogger
// Utilities
Sync() error
}
Logger represents the logging interface
func DatabaseQueryLogger ¶
func DatabaseQueryLogger(logger Logger, query, table string, rows int64, duration time.Duration) Logger
DatabaseQueryLogger creates a logger with database query fields
func GetGlobalLogger ¶
func GetGlobalLogger() Logger
GetGlobalLogger returns the global logger instance
func HTTPRequestLogger ¶
HTTPRequestLogger creates a logger with HTTP request fields
func LoggerFromContext ¶
LoggerFromContext extracts a logger from the context
func NewDevelopmentLogger ¶
func NewDevelopmentLogger() Logger
NewDevelopmentLogger creates a development logger with enhanced colors
func NewDevelopmentLoggerWithLevel ¶
NewDevelopmentLoggerWithLevel creates a development logger with specified level
func NewLogger ¶
func NewLogger(config LoggingConfig) Logger
NewLogger creates a new logger with the given configuration
func NewProductionLogger ¶
func NewProductionLogger() Logger
NewProductionLogger creates a production logger
func NewTestLogger ¶
func NewTestLogger() Logger
func ServiceLogger ¶
ServiceLogger creates a logger with service information fields
type LoggingConfig ¶
type LoggingConfig struct {
Level LogLevel `mapstructure:"level" yaml:"level" env:"FORGE_LOG_LEVEL"`
Format string `mapstructure:"format" yaml:"format" env:"FORGE_LOG_FORMAT"`
Environment string `mapstructure:"environment" yaml:"environment" env:"FORGE_ENVIRONMENT"`
Output string `mapstructure:"output" yaml:"output" env:"FORGE_LOG_OUTPUT"`
}
LoggingConfig represents logging configuration
type LoggingWriter ¶
type LoggingWriter struct {
// contains filtered or unexported fields
}
LoggingWriter is an io.Writer that logs each write
func NewLoggingWriter ¶
func NewLoggingWriter(logger Logger, level string) *LoggingWriter
NewLoggingWriter creates a new logging writer
type PerformanceMonitor ¶
type PerformanceMonitor struct {
// contains filtered or unexported fields
}
PerformanceMonitor helps monitor performance metrics
func NewPerformanceMonitor ¶
func NewPerformanceMonitor(logger Logger, operation string) *PerformanceMonitor
NewPerformanceMonitor creates a new performance monitor
func (*PerformanceMonitor) Finish ¶
func (pm *PerformanceMonitor) Finish()
Finish logs the completion of the monitored operation
func (*PerformanceMonitor) FinishWithError ¶
func (pm *PerformanceMonitor) FinishWithError(err error)
FinishWithError logs the completion of the monitored operation with an error
func (*PerformanceMonitor) WithField ¶
func (pm *PerformanceMonitor) WithField(field Field) *PerformanceMonitor
WithField adds a field to the performance monitor
func (*PerformanceMonitor) WithFields ¶
func (pm *PerformanceMonitor) WithFields(fields ...Field) *PerformanceMonitor
WithFields adds multiple fields to the performance monitor
type StructuredLog ¶
type StructuredLog struct {
// contains filtered or unexported fields
}
StructuredLog provides a fluent interface for structured logging
func NewStructuredLog ¶
func NewStructuredLog(logger Logger) *StructuredLog
NewStructuredLog creates a new structured log
func (*StructuredLog) Logger ¶
func (sl *StructuredLog) Logger() Logger
Logger returns a logger with all accumulated fields
func (*StructuredLog) WithContext ¶
func (sl *StructuredLog) WithContext(ctx context.Context) *StructuredLog
WithContext adds context fields to the structured log
func (*StructuredLog) WithDatabaseQuery ¶
func (sl *StructuredLog) WithDatabaseQuery(query, table string, rows int64, duration time.Duration) *StructuredLog
WithDatabaseQuery adds database query fields
func (*StructuredLog) WithField ¶
func (sl *StructuredLog) WithField(field Field) *StructuredLog
WithField adds a field to the structured log
func (*StructuredLog) WithFields ¶
func (sl *StructuredLog) WithFields(fields ...Field) *StructuredLog
WithFields adds multiple fields to the structured log
func (*StructuredLog) WithGroup ¶
func (sl *StructuredLog) WithGroup(group *FieldGroup) *StructuredLog
WithGroup adds a field group to the structured log
func (*StructuredLog) WithHTTPRequest ¶
func (sl *StructuredLog) WithHTTPRequest(method, path, userAgent string, status int) *StructuredLog
WithHTTPRequest adds HTTP request fields
func (*StructuredLog) WithService ¶
func (sl *StructuredLog) WithService(name, version, environment string) *StructuredLog
WithService adds service information fields
type SugarLogger ¶
type SugarLogger interface {
Debugw(msg string, keysAndValues ...interface{})
Infow(msg string, keysAndValues ...interface{})
Warnw(msg string, keysAndValues ...interface{})
Errorw(msg string, keysAndValues ...interface{})
Fatalw(msg string, keysAndValues ...interface{})
With(args ...interface{}) SugarLogger
}
SugarLogger provides a more flexible API
type TestLogger ¶
type TestLogger struct {
// contains filtered or unexported fields
}
TestLogger provides a test logger implementation
func (*TestLogger) AssertHasLog ¶
func (tl *TestLogger) AssertHasLog(level, message string) bool
AssertLogs checks if expected logs were recorded (only works with TestLogger)
func (*TestLogger) CountLogs ¶
func (tl *TestLogger) CountLogs(level string) int
CountLogs returns count of logs at a specific level
func (*TestLogger) Debug ¶
func (tl *TestLogger) Debug(msg string, fields ...Field)
Debug logs a debug message
func (*TestLogger) Debugf ¶
func (tl *TestLogger) Debugf(template string, args ...interface{})
func (*TestLogger) Error ¶
func (tl *TestLogger) Error(msg string, fields ...Field)
Error logs an error message
func (*TestLogger) Errorf ¶
func (tl *TestLogger) Errorf(template string, args ...interface{})
func (*TestLogger) Fatal ¶
func (tl *TestLogger) Fatal(msg string, fields ...Field)
func (*TestLogger) Fatalf ¶
func (tl *TestLogger) Fatalf(template string, args ...interface{})
func (*TestLogger) GetLogs ¶
func (tl *TestLogger) GetLogs() []LogEntry
GetLogs returns all logged entries
func (*TestLogger) GetLogsByLevel ¶
func (tl *TestLogger) GetLogsByLevel(level string) []LogEntry
GetLogsByLevel returns logs filtered by level
func (*TestLogger) Info ¶
func (tl *TestLogger) Info(msg string, fields ...Field)
Info logs an info message
func (*TestLogger) Infof ¶
func (tl *TestLogger) Infof(template string, args ...interface{})
func (*TestLogger) Named ¶
func (tl *TestLogger) Named(name string) Logger
func (*TestLogger) Sugar ¶
func (tl *TestLogger) Sugar() SugarLogger
func (*TestLogger) Sync ¶
func (tl *TestLogger) Sync() error
func (*TestLogger) Warn ¶
func (tl *TestLogger) Warn(msg string, fields ...Field)
Warn logs a warning message
func (*TestLogger) Warnf ¶
func (tl *TestLogger) Warnf(template string, args ...interface{})
func (*TestLogger) With ¶
func (tl *TestLogger) With(fields ...Field) Logger
func (*TestLogger) WithContext ¶
func (tl *TestLogger) WithContext(ctx context.Context) Logger
WithContext returns a logger with context