Documentation
¶
Index ¶
- Constants
- func CloseAllWriters() error
- func Colorize(color Color, text string) string
- func Colorizef(color Color, format string, args ...any) string
- func CusTimeEncoder(config Config) zapcore.TimeEncoder
- func Debug(msg string, fields ...zap.Field)
- func Debugf(format string, args ...any)
- func Error(msg string, fields ...zap.Field)
- func Errorf(format string, args ...any)
- func Fatal(msg string, fields ...zap.Field)
- func Fatalf(format string, args ...any)
- func GetEncoder(config Config) zapcore.Encoder
- func GetRequestID(ctx context.Context) string
- func GetSpanID(ctx context.Context) string
- func GetTraceID(ctx context.Context) string
- func GetUserID(ctx context.Context) string
- func HTTPMiddleware(logger Logger) func(http.Handler) http.Handler
- func Info(msg string, fields ...zap.Field)
- func Infof(format string, args ...any)
- func Init(config Config)
- func Pad(color Color, text string, width int) string
- func PadLeft(color Color, text string, width int) string
- func RecoveryMiddleware(logger Logger) func(http.Handler) http.Handler
- func SetGlobal(logger Logger)
- func SetRequestID(ctx context.Context, requestID string) context.Context
- func SetSpanID(ctx context.Context, spanID string) context.Context
- func SetTraceID(ctx context.Context, traceID string) context.Context
- func SetUserID(ctx context.Context, userID string) context.Context
- func Styled(text string, colors ...Color) string
- func Styledf(format string, colors []Color, args ...any) string
- func Sync() error
- func ToContext(ctx context.Context, logger Logger) context.Context
- func Warn(msg string, fields ...zap.Field)
- func Warnf(format string, args ...any)
- type Color
- type ColorScheme
- type Config
- type DefaultColorScheme
- type Factory
- type Hook
- type Logger
- func FromContext(ctx context.Context) Logger
- func FromZap(zl *zap.Logger) Logger
- func Global() Logger
- func Named(name string) Logger
- func NewLogger(config Config) Logger
- func With(fields ...zap.Field) Logger
- func WithContext(logger Logger, ctx context.Context) Logger
- func WithError(err error) Logger
- func WithHook(logger Logger, hook Hook) Logger
- func WithHooks(logger Logger, hooks ...Hook) Logger
Constants ¶
const ( // TraceIDKey is the context key for trace ID. TraceIDKey ctxKey = "trace_id" // SpanIDKey is the context key for span ID. SpanIDKey ctxKey = "span_id" // RequestIDKey is the context key for request ID. RequestIDKey ctxKey = "request_id" // UserIDKey is the context key for user ID. UserIDKey ctxKey = "user_id" )
Variables ¶
This section is empty.
Functions ¶
func CusTimeEncoder ¶
func CusTimeEncoder(config Config) zapcore.TimeEncoder
CusTimeEncoder creates a custom time encoder that adds the prefix and formats the time.
func GetEncoder ¶
GetEncoder returns a zapcore.Encoder based on the config format.
func GetRequestID ¶
GetRequestID extracts request ID from context.
func GetTraceID ¶
GetTraceID extracts trace ID from context.
func HTTPMiddleware ¶
HTTPMiddleware returns an HTTP middleware that logs requests.
func RecoveryMiddleware ¶
RecoveryMiddleware returns an HTTP middleware that recovers from panics and logs them.
func SetGlobal ¶
func SetGlobal(logger Logger)
SetGlobal replaces the global logger with the given logger.
func SetRequestID ¶
SetRequestID adds request ID to context.
func SetTraceID ¶
SetTraceID adds trace ID to context.
func Styled ¶
Styled applies combined colors to text and resets. Example: Styled("ERROR", BoldWhite, BgRed) -> bold white "ERROR" on red background.
Types ¶
type Color ¶
type Color = string
Color represents a terminal ANSI color escape code.
const ( Black Color = "\033[30m" Red Color = "\033[31m" Green Color = "\033[32m" Yellow Color = "\033[33m" Blue Color = "\033[34m" Purple Color = "\033[35m" Cyan Color = "\033[36m" White Color = "\033[37m" Gray Color = "\033[90m" Default Color = "\033[39m" )
Foreground colors
const ( BoldBlack Color = "\033[1;30m" BoldRed Color = "\033[1;31m" BoldGreen Color = "\033[1;32m" BoldYellow Color = "\033[1;33m" BoldBlue Color = "\033[1;34m" BoldPurple Color = "\033[1;35m" BoldCyan Color = "\033[1;36m" BoldWhite Color = "\033[1;37m" BoldGray Color = "\033[1;90m" BoldDefault Color = "\033[1;39m" )
Bold foreground colors
const ( BgBlack Color = "\033[40m" BgRed Color = "\033[41m" BgGreen Color = "\033[42m" BgYellow Color = "\033[43m" BgBlue Color = "\033[44m" BgPurple Color = "\033[45m" BgCyan Color = "\033[46m" BgWhite Color = "\033[47m" BgGray Color = "\033[100m" BgDefault Color = "\033[49m" )
Background colors
const ( BgBrightBlack Color = "\033[100m" BgBrightRed Color = "\033[101m" BgBrightGreen Color = "\033[102m" BgBrightYellow Color = "\033[103m" BgBrightBlue Color = "\033[104m" BgBrightPurple Color = "\033[105m" BgBrightCyan Color = "\033[106m" BgBrightWhite Color = "\033[107m" )
Bright background colors (high intensity)
const ( Bold Color = "\033[1m" Dim Color = "\033[2m" Italic Color = "\033[3m" Underline Color = "\033[4m" Blink Color = "\033[5m" Reverse Color = "\033[7m" Hidden Color = "\033[8m" Strike Color = "\033[9m" )
Text styles
const (
Reset Color = "\033[0m"
)
Reset code
type ColorScheme ¶
type ColorScheme interface {
// StatusColor returns the color for an HTTP status code.
StatusColor(code int) Color
// MethodColor returns the color for an HTTP method.
MethodColor(method string) Color
// DurationColor returns the color based on request duration.
DurationColor(d time.Duration) Color
// LevelColor returns the color for a log level.
LevelColor(level string) Color
}
ColorScheme maps semantic elements to colors. Implement this interface to fully customize color behavior.
type Config ¶
type Config struct {
// Director is the directory where log files will be stored.
Director string `mapstructure:"director" json:"director" yaml:"director" toml:"director"`
// MessageKey is the JSON key for the message field.
MessageKey string `mapstructure:"message-key" json:"messageKey" yaml:"message-key" toml:"message-key"`
// LevelKey is the JSON key for the level field.
LevelKey string `mapstructure:"level-key" json:"levelKey" yaml:"level-key" toml:"level-key"`
// TimeKey is the JSON key for the timestamp field.
TimeKey string `mapstructure:"time-key" json:"timeKey" yaml:"time-key" toml:"time-key"`
// NameKey is the JSON key for the logger name field.
NameKey string `mapstructure:"name-key" json:"nameKey" yaml:"name-key" toml:"name-key"`
// CallerKey is the JSON key for the caller field.
CallerKey string `mapstructure:"caller-key" json:"callerKey" yaml:"caller-key" toml:"caller-key"`
// LineEnding is the line ending character(s).
LineEnding string `mapstructure:"line-ending" json:"lineEnding" yaml:"line-ending" toml:"line-ending"`
// StacktraceKey is the JSON key for the stacktrace field.
StacktraceKey string `mapstructure:"stacktrace-key" json:"stacktraceKey" yaml:"stacktrace-key" toml:"stacktrace-key"`
// Level is the minimum log level (debug, info, warn, error, dpanic, panic, fatal).
Level string `mapstructure:"level" json:"level" yaml:"level" toml:"level"`
// EncodeLevel is the level encoder type (LowercaseLevelEncoder, LowercaseColorLevelEncoder, CapitalLevelEncoder, CapitalColorLevelEncoder).
EncodeLevel string `mapstructure:"encode-level" json:"encodeLevel" yaml:"encode-level" toml:"encode-level"`
// Prefix is the prefix to prepend to each log line.
Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix" toml:"prefix"`
// TimeFormat is the time format string (uses Go time format).
TimeFormat string `mapstructure:"time-format" json:"timeFormat" yaml:"time-format" toml:"time-format"`
// Format is the log format (json or console).
Format string `mapstructure:"format" json:"format" yaml:"format" toml:"format"`
// LogInTerminal enables logging to terminal in addition to file.
LogInTerminal bool `mapstructure:"log-in-terminal" json:"logInTerminal" yaml:"log-in-terminal" toml:"log-in-terminal"`
// MaxAge is the maximum number of days to retain old log files.
MaxAge int `mapstructure:"max-age" json:"maxAge" yaml:"max-age" toml:"max-age"`
// MaxSize is the maximum size in megabytes of the log file before it gets rotated.
MaxSize int `mapstructure:"max-size" json:"maxSize" yaml:"max-size" toml:"max-size"`
// MaxBackups is the maximum number of old log files to retain.
MaxBackups int `mapstructure:"max-backups" json:"maxBackups" yaml:"max-backups" toml:"max-backups"`
// Compress determines if the rotated log files should be compressed using gzip.
Compress bool `mapstructure:"compress" json:"compress" yaml:"compress" toml:"compress"`
// ShowLineNumber enables adding caller information to log entries.
ShowLineNumber bool `mapstructure:"show-line-number" json:"showLineNumber" yaml:"show-line-number" toml:"show-line-number"`
}
Config represents the logger configuration.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults.
func (Config) TransportLevel ¶
TransportLevel converts the string level to zapcore.Level.
func (Config) ZapEncodeLevel ¶
func (c Config) ZapEncodeLevel() zapcore.LevelEncoder
ZapEncodeLevel returns the zapcore.LevelEncoder based on EncodeLevel.
type DefaultColorScheme ¶
type DefaultColorScheme struct {
// Status code colors (foreground + optional background)
Status1xx Color // Informational
Status2xx Color // Success
Status3xx Color // Redirection
Status4xx Color // Client Error
Status5xx Color // Server Error
// HTTP method colors
MethodGET Color
MethodPOST Color
MethodPUT Color
MethodDELETE Color
MethodPATCH Color
MethodHEAD Color
MethodOPTIONS Color
// Duration thresholds and colors
DurationFast Color // < FastThreshold
DurationMedium Color // FastThreshold <= d < SlowThreshold
DurationSlow Color // >= SlowThreshold
DurationFastThreshold time.Duration // Default: 100ms
DurationSlowThreshold time.Duration // Default: 500ms
// Log level colors
LevelDebug Color
LevelInfo Color
LevelWarn Color
LevelError Color
LevelFatal Color
}
DefaultColorScheme provides configurable color mappings with sensible defaults. Override individual fields to customize specific colors. Zero values fall back to sensible defaults.
func NewBackgroundColorScheme ¶
func NewBackgroundColorScheme() *DefaultColorScheme
NewBackgroundColorScheme returns a scheme using background colors for emphasis. Great for status codes and log levels that need to stand out.
func NewBoldColorScheme ¶
func NewBoldColorScheme() *DefaultColorScheme
NewBoldColorScheme returns a scheme with bold foreground colors.
func NewDefaultColorScheme ¶
func NewDefaultColorScheme() *DefaultColorScheme
NewDefaultColorScheme returns a scheme with sensible defaults. All colors use foreground only. Customize fields for background colors.
func (*DefaultColorScheme) DurationColor ¶
func (s *DefaultColorScheme) DurationColor(d time.Duration) Color
DurationColor returns the color based on request duration.
func (*DefaultColorScheme) LevelColor ¶
func (s *DefaultColorScheme) LevelColor(level string) Color
LevelColor returns the color for a log level.
func (*DefaultColorScheme) MethodColor ¶
func (s *DefaultColorScheme) MethodColor(method string) Color
MethodColor returns the color for an HTTP method.
func (*DefaultColorScheme) StatusColor ¶
func (s *DefaultColorScheme) StatusColor(code int) Color
StatusColor returns the color for an HTTP status code.
type Factory ¶
type Factory struct {
// contains filtered or unexported fields
}
Factory creates and manages named loggers.
func NewFactory ¶
NewFactory creates a new Factory with the given config.
type Hook ¶
Hook is a function that is called for each log entry. It can be used for custom log processing, alerting, metrics, etc.
type Logger ¶
type Logger interface {
// Debug logs a message at DebugLevel.
Debug(msg string, fields ...zap.Field)
// Info logs a message at InfoLevel.
Info(msg string, fields ...zap.Field)
// Warn logs a message at WarnLevel.
Warn(msg string, fields ...zap.Field)
// Error logs a message at ErrorLevel.
Error(msg string, fields ...zap.Field)
// Fatal logs a message at FatalLevel and then calls os.Exit(1).
Fatal(msg string, fields ...zap.Field)
// Debugf logs a formatted message at DebugLevel.
Debugf(format string, args ...any)
// Infof logs a formatted message at InfoLevel.
Infof(format string, args ...any)
// Warnf logs a formatted message at WarnLevel.
Warnf(format string, args ...any)
// Errorf logs a formatted message at ErrorLevel.
Errorf(format string, args ...any)
// Fatalf logs a formatted message at FatalLevel and then calls os.Exit(1).
Fatalf(format string, args ...any)
// With creates a child logger with additional fields.
With(fields ...zap.Field) Logger
// WithError creates a child logger with an error field.
WithError(err error) Logger
// Named creates a child logger with the given name.
Named(name string) Logger
// Zap returns the underlying *zap.Logger.
Zap() *zap.Logger
// Sugar returns the underlying *zap.SugaredLogger.
Sugar() *zap.SugaredLogger
// Sync flushes any buffered log entries.
Sync() error
}
Logger is the interface for structured logging.
func FromContext ¶
FromContext returns the Logger stored in the context, or the global logger if none.
func WithContext ¶
WithContext creates a child logger with fields extracted from the context. It extracts trace_id, span_id, request_id, and user_id if present.