Documentation
¶
Overview ¶
Package logger provides a production-ready structured logging solution built on Uber's Zap. It supports environment-aware configuration, context propagation with trace IDs, log sampling, and graceful shutdown.
Index ¶
- Constants
- func CacheHit(hit bool) zap.Field
- func CacheKey(key string) zap.Field
- func ClientIP(ip string) zap.Field
- func Component(name string) zap.Field
- func DBDuration(d time.Duration) zap.Field
- func DBOperation(op string) zap.Field
- func DBTable(table string) zap.Field
- func Environment(env string) zap.Field
- func Error(err error) zap.Field
- func ErrorCode(code string) zap.Field
- func ErrorType(err error) zap.Field
- func FromContext(ctx context.Context) *zap.Logger
- func FromOtelContext(ctx context.Context) *zap.Logger
- func GRPCCode(code string) zap.Field
- func GRPCMethod(method string) zap.Field
- func GRPCService(service string) zap.Field
- func Global() *zap.Logger
- func GlobalLevel() zap.AtomicLevel
- func HTTPMiddleware(log *zap.Logger) func(http.Handler) http.Handler
- func Latency(d time.Duration) zap.Field
- func LatencyMs(d time.Duration) zap.Field
- func LoggerWithSpan(log *zap.Logger, span trace.Span) *zap.Logger
- func MessageID(id string) zap.Field
- func Method(method string) zap.Field
- func New(ctx context.Context, serviceName string, cfg Config, w io.Writer) *zap.Logger
- func NewWithLevel(ctx context.Context, serviceName string, cfg Config, w io.Writer) (*zap.Logger, zap.AtomicLevel)
- func Operation(name string) zap.Field
- func ParentSpanID(id string) zap.Field
- func Path(path string) zap.Field
- func QueueName(name string) zap.Field
- func RecoveryMiddleware(log *zap.Logger) func(http.Handler) http.Handler
- func RequestID(id string) zap.Field
- func RequestSize(size int64) zap.Field
- func ResponseSize(size int) zap.Field
- func RowsAffected(n int64) zap.Field
- func SessionID(id string) zap.Field
- func SetGlobalLevel(level string)
- func SpanID(id string) zap.Field
- func StatusCode(code int) zap.Field
- func TenantID(id string) zap.Field
- func TraceEvent(log *zap.Logger, span trace.Span, msg string, fields ...zap.Field)
- func TraceID(id string) zap.Field
- func UserAgent(ua string) zap.Field
- func UserID(id string) zap.Field
- func Version(v string) zap.Field
- func WithContext(ctx context.Context, l *zap.Logger) context.Context
- func WithError(l *zap.Logger, err error) *zap.Logger
- func WithOtelContext(ctx context.Context, log *zap.Logger) *zap.Logger
- func WithTraceID(l *zap.Logger, traceID, spanID string) *zap.Logger
- type Config
- type OtelCore
- type SamplingConfig
Constants ¶
const ( EnvLocal = "local" EnvProd = "prod" EnvDev = "dev" )
Variables ¶
This section is empty.
Functions ¶
func DBOperation ¶
Database fields for database operation logging.
func FromContext ¶
FromContext retrieves the logger from context, or returns the global logger.
func FromOtelContext ¶
FromOtelContext retrieves the logger from context and enriches it with OpenTelemetry trace information if available.
func GRPCService ¶
func GlobalLevel ¶
func GlobalLevel() zap.AtomicLevel
GlobalLevel returns the global logger's AtomicLevel for dynamic level control.
func HTTPMiddleware ¶
HTTPMiddleware returns a middleware that logs HTTP requests. It captures method, path, status, latency, and request metadata.
func LoggerWithSpan ¶
LoggerWithSpan creates a new logger with span information attached. This is useful when you want to correlate logs with a specific span.
func New ¶
New creates a new *zap.Logger based on the provided configuration. The serviceName is added as a permanent field to all log entries. If w is provided, logs will also be written to it (useful for testing).
Output behavior:
- All environments: Human-readable console output to stdout
- Dev/Prod with ExportPath: Additional JSON output for log aggregation
func NewWithLevel ¶
func NewWithLevel(ctx context.Context, serviceName string, cfg Config, w io.Writer) (*zap.Logger, zap.AtomicLevel)
NewWithLevel creates a new *zap.Logger and returns its AtomicLevel for dynamic level control. Use this when you need to change the log level at runtime.
func ParentSpanID ¶
func RecoveryMiddleware ¶
RecoveryMiddleware returns a middleware that recovers from panics and logs them.
func RequestSize ¶
func ResponseSize ¶
func RowsAffected ¶
func SetGlobalLevel ¶
func SetGlobalLevel(level string)
SetGlobalLevel dynamically changes the global logger's level.
func StatusCode ¶
func TraceEvent ¶
TraceEvent logs a trace event as a zap log entry. This helps correlate application logs with distributed traces.
func WithContext ¶
WithContext returns a new context with the logger attached.
func WithOtelContext ¶
WithOtelContext extracts trace and span IDs from an OpenTelemetry context and returns a logger with those fields attached.
Types ¶
type Config ¶
type Config struct {
// Level is the minimum enabled logging level.
// Valid values: debug, info, warn, error, dpanic, panic, fatal
Level string `yaml:"level" json:"level" mapstructure:"level"`
// Environment controls logger behavior.
// "local" - only human-readable console output
// "dev", "prod" - human-readable console + optional JSON export
Environment string `yaml:"environment" json:"environment" mapstructure:"environment"`
// ExportPath is an optional path for JSON log export (only for dev/prod).
// Can be a file path or "stdout"/"stderr".
// If empty, JSON export is disabled.
ExportPath string `yaml:"export_path" json:"export_path" mapstructure:"export_path"`
// ExportWriter is an optional writer for JSON log export.
// When set, JSON-encoded logs are written here in addition to console output.
// Use this to pipe logs directly into ClickHouse, Loki, Kafka, etc.
// Takes precedence over ExportPath. Works in any environment.
ExportWriter io.Writer `yaml:"-" json:"-" mapstructure:"-"`
// Sampling configures log sampling for high-throughput applications.
Sampling *SamplingConfig `yaml:"sampling,omitempty" json:"sampling" mapstructure:"sampling"`
// DisableCaller stops annotating logs with the calling function's file name and line number.
DisableCaller bool `yaml:"disable_caller" json:"disable_caller" mapstructure:"disable_caller"`
// DisableStacktrace disables automatic stacktrace capturing.
DisableStacktrace bool `yaml:"disable_stacktrace" json:"disable_stacktrace" mapstructure:"disable_stacktrace"`
// StacktraceLevel is the minimum level at which stacktraces are captured.
// Valid values: debug, info, warn, error, dpanic, panic, fatal
StacktraceLevel string `yaml:"stacktrace_level" json:"stacktrace_level" mapstructure:"stacktrace_level"`
}
Config holds configuration for the application logger.
func DefaultLoggerConfig ¶
func DefaultLoggerConfig() Config
DefaultLoggerConfig returns a sensible default configuration.
type OtelCore ¶
OtelCore is a zapcore.Core wrapper that automatically adds trace context. Use this when you want all logs to automatically include trace IDs.
type SamplingConfig ¶
type SamplingConfig struct {
// Initial is the number of entries with the same level and message to log per second.
Initial int `yaml:"initial"`
// Thereafter is the number of entries to drop for each duplicate after Initial.
Thereafter int `yaml:"thereafter"`
}
SamplingConfig sets a sampling policy for repeated log entries.