Documentation
¶
Index ¶
- Constants
- func ContextWithFields(ctx context.Context, requestID string, userID uint, traceID string) context.Context
- func Debug(msg string, fields ...zap.Field)
- func DebugCtx(ctx context.Context, msg string, fields ...zap.Field)
- func Error(msg string, fields ...zap.Field)
- func ErrorCtx(ctx context.Context, msg string, fields ...zap.Field)
- func Fatal(msg string, fields ...zap.Field)
- func FromContext(ctx context.Context) *zap.Logger
- func GinMiddleware(opts ...GinOptionFunc) gin.HandlerFunc
- func Info(msg string, fields ...zap.Field)
- func InfoCtx(ctx context.Context, msg string, fields ...zap.Field)
- func Init(cfg Config) error
- func InitWithDefaults() error
- func L() *zap.Logger
- func Panic(msg string, fields ...zap.Field)
- func S() *zap.SugaredLogger
- func Sync() error
- func Warn(msg string, fields ...zap.Field)
- func WarnCtx(ctx context.Context, msg string, fields ...zap.Field)
- func With(fields ...zap.Field) *zap.Logger
- func WithRequestID(ctx context.Context, requestID string) context.Context
- func WithTraceID(ctx context.Context, traceID string) context.Context
- func WithUserID(ctx context.Context, userID uint) context.Context
- type Config
- func (c *Config) Validate() error
- func (c Config) WithAppName(name string) Config
- func (c Config) WithConsole(enabled bool) Config
- func (c Config) WithEnvironment(env string) Config
- func (c Config) WithFile(path string) Config
- func (c Config) WithFileRotation(maxSizeMB, maxBackups, maxAgeDays int, compress bool) Config
- func (c Config) WithLevel(level string) Config
- func (c Config) WithTimezone(loc *time.Location) Config
- func (c Config) WithVersion(version string) Config
- type GinConfig
- type GinOptionFunc
- func WithLogRequestBody(enabled bool) GinOptionFunc
- func WithLogResponseBody(enabled bool) GinOptionFunc
- func WithMaskPatterns(patterns ...string) GinOptionFunc
- func WithMaxBodyLogSize(size int) GinOptionFunc
- func WithRequestIDHeader(header string) GinOptionFunc
- func WithSkipPaths(paths ...string) GinOptionFunc
- func WithUUIDv7(enabled bool) GinOptionFunc
- type GormConfig
- type GormLogger
- func (l *GormLogger) Error(ctx context.Context, msg string, data ...interface{})
- func (l *GormLogger) Info(ctx context.Context, msg string, data ...interface{})
- func (l *GormLogger) LogMode(level gormlogger.LogLevel) gormlogger.Interface
- func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)
- func (l *GormLogger) Warn(ctx context.Context, msg string, data ...interface{})
- type GormOption
Constants ¶
const ( // RequestIDKey is the context key for request ID. RequestIDKey contextKey = "request_id" // UserIDKey is the context key for user ID. UserIDKey contextKey = "user_id" // TraceIDKey is the context key for trace ID. TraceIDKey contextKey = "trace_id" )
const DefaultMaskValue = "******"
DefaultMaskValue is the default replacement for masked fields.
Variables ¶
This section is empty.
Functions ¶
func ContextWithFields ¶
func ContextWithFields(ctx context.Context, requestID string, userID uint, traceID string) context.Context
ContextWithFields adds multiple fields to the context at once.
func FromContext ¶
FromContext returns a logger with context fields (request_id, user_id, trace_id). If no context is provided or no fields are found, returns the global logger.
func GinMiddleware ¶
func GinMiddleware(opts ...GinOptionFunc) gin.HandlerFunc
GinMiddleware returns a Gin middleware that logs HTTP requests.
func InitWithDefaults ¶
func InitWithDefaults() error
InitWithDefaults initializes the logger with default configuration.
func WithRequestID ¶
WithRequestID adds a request ID to the context.
func WithTraceID ¶
WithTraceID adds a trace ID to the context.
Types ¶
type Config ¶
type Config struct {
// Environment determines the log format.
// "development" uses colored console output, "production" uses JSON format.
Environment string
// Level sets the minimum log level.
// Valid values: "debug", "info", "warn", "error"
Level string
// AppName is used as the service identifier in structured logs.
AppName string
// Version is the application version for structured logs.
Version string
// File output configuration
EnableFile bool // Enable file output
FilePath string // Path to log file (e.g., "logs/app.log")
MaxSizeMB int // Maximum size in MB before rotation
MaxBackups int // Number of old files to keep (0 = unlimited)
MaxAgeDays int // Maximum age in days to keep (0 = unlimited)
Compress bool // Compress rotated files
// Console output
EnableConsole bool // Enable console (stdout) output
// Timezone for log timestamps
Timezone *time.Location
}
Config contains all configuration options for the logger.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults. - Environment: "development" - Level: "info" - EnableConsole: true - EnableFile: false - Timezone: Vietnam (UTC+7)
func (Config) WithAppName ¶
WithAppName sets the application name.
func (Config) WithConsole ¶
WithConsole enables or disables console output.
func (Config) WithEnvironment ¶
WithEnvironment sets the environment.
func (Config) WithFileRotation ¶
WithFileRotation configures file rotation settings.
func (Config) WithTimezone ¶
WithTimezone sets the timezone for log timestamps.
func (Config) WithVersion ¶ added in v1.0.1
WithVersion sets the application version.
type GinConfig ¶
type GinConfig struct {
// RequestIDHeader is the header key for request ID.
// Default: "X-Request-ID"
RequestIDHeader string
// MaxBodyLogSize limits the size of request/response body to log.
// Default: 4096 bytes
MaxBodyLogSize int
// LogRequestBody enables logging request body on errors (>= 400).
// Default: true
LogRequestBody bool
// LogResponseBody enables logging response body on errors (>= 400).
// Default: true
LogResponseBody bool
// SkipPaths is a list of paths to skip logging.
SkipPaths []string
// UseUUIDv7 uses UUID v7 (time-ordered) for request IDs.
// Default: true
UseUUIDv7 bool
// MaskPatterns is a list of compiled regex patterns for field names to mask.
// Values of fields whose names match any pattern will be replaced with "******".
MaskPatterns []*regexp.Regexp
}
GinConfig contains configuration for the Gin middleware.
func DefaultGinConfig ¶
func DefaultGinConfig() GinConfig
DefaultGinConfig returns a GinConfig with sensible defaults.
type GinOptionFunc ¶
type GinOptionFunc func(*GinConfig)
GinOptionFunc is a function that configures GinConfig.
func WithLogRequestBody ¶
func WithLogRequestBody(enabled bool) GinOptionFunc
WithLogRequestBody enables/disables request body logging.
func WithLogResponseBody ¶
func WithLogResponseBody(enabled bool) GinOptionFunc
WithLogResponseBody enables/disables response body logging.
func WithMaskPatterns ¶ added in v1.2.0
func WithMaskPatterns(patterns ...string) GinOptionFunc
WithMaskPatterns sets regex patterns for field names to mask in request/response bodies. Values of JSON fields whose names match any pattern will be replaced with "******". Example: WithMaskPatterns(`(?i)password`, `(?i)secret`, `(?i)token`)
func WithMaxBodyLogSize ¶
func WithMaxBodyLogSize(size int) GinOptionFunc
WithMaxBodyLogSize sets the maximum body size to log.
func WithRequestIDHeader ¶
func WithRequestIDHeader(header string) GinOptionFunc
WithRequestIDHeader sets the request ID header name.
func WithSkipPaths ¶
func WithSkipPaths(paths ...string) GinOptionFunc
WithSkipPaths sets paths to skip logging.
func WithUUIDv7 ¶
func WithUUIDv7(enabled bool) GinOptionFunc
WithUUIDv7 enables/disables UUID v7 for request IDs.
type GormConfig ¶
type GormConfig struct {
// SlowThreshold is the threshold for marking queries as "slow".
// Default: 200ms
SlowThreshold time.Duration
// IgnoreRecordNotFound skips logging ErrRecordNotFound errors.
// Default: true
IgnoreRecordNotFound bool
// LogLevel sets the GORM log level.
// Default: gormlogger.Warn
LogLevel gormlogger.LogLevel
}
GormConfig contains configuration for the GORM logger adapter.
func DefaultGormConfig ¶
func DefaultGormConfig() GormConfig
DefaultGormConfig returns a GormConfig with sensible defaults.
type GormLogger ¶
type GormLogger struct {
// contains filtered or unexported fields
}
GormLogger is a custom GORM logger that uses tlog.
func NewGormLogger ¶
func NewGormLogger(opts ...GormOption) *GormLogger
NewGormLogger creates a new GORM logger adapter.
func (*GormLogger) Error ¶
func (l *GormLogger) Error(ctx context.Context, msg string, data ...interface{})
Error logs error messages.
func (*GormLogger) Info ¶
func (l *GormLogger) Info(ctx context.Context, msg string, data ...interface{})
Info logs informational messages.
func (*GormLogger) LogMode ¶
func (l *GormLogger) LogMode(level gormlogger.LogLevel) gormlogger.Interface
LogMode sets the log level and returns a new logger.
type GormOption ¶
type GormOption func(*GormConfig)
GormOption is a function that configures GormConfig.
func WithGormLogLevel ¶
func WithGormLogLevel(level gormlogger.LogLevel) GormOption
WithGormLogLevel sets the GORM log level.
func WithIgnoreRecordNotFound ¶
func WithIgnoreRecordNotFound(ignore bool) GormOption
WithIgnoreRecordNotFound sets whether to ignore ErrRecordNotFound.
func WithSlowThreshold ¶
func WithSlowThreshold(d time.Duration) GormOption
WithSlowThreshold sets the slow query threshold.