Documentation
¶
Overview ¶
Package logger provides structured logging for LingByte.
Initialization:
Call logger.InitTimezone(constants.TimezoneShanghai) once at startup to set the process-wide time.Local, then call logger.Init(&cfg.Log, cfg.Server.Mode) to configure the zap logger. InitTimezone must run before Init so timestamps and daily log rotation boundaries use the correct timezone.
Features:
- JSON file output with lumberjack rotation (optional daily filenames)
- Colored console output in local/dev/prod modes (stdout info, stderr error)
- Sensitive field redaction (LOG_SENSITIVE_FIELDS)
- Request ID prefixing and Gin helpers (FromGin, GinZapFields)
- Context-aware logging (InfoCtx, ErrorCtx, ...)
- SafeGo for panic-safe background goroutines
- Log retention purge (PurgeExpiredLogFiles)
Index ¶
- Constants
- Variables
- func Close()
- func Debug(msg string, fields ...zap.Field)
- func DebugCtx(ctx context.Context, msg string, fields ...zap.Field)
- func Debugf(format string, args ...interface{})
- func DebugfCtx(ctx context.Context, format string, args ...interface{})
- func Error(msg string, fields ...zap.Field)
- func ErrorCtx(ctx context.Context, msg string, fields ...zap.Field)
- func ErrorWithRedactedFields(msg string, fields map[string]interface{})
- func Errorf(format string, args ...interface{})
- func ErrorfCtx(ctx context.Context, format string, args ...interface{})
- func Fatal(msg string, fields ...zap.Field)
- func FatalCtx(ctx context.Context, msg string, fields ...zap.Field)
- func Fatalf(format string, args ...interface{})
- func FatalfCtx(ctx context.Context, format string, args ...interface{})
- func GenReqID() string
- func GetDailyLogFilename(baseFilename string) string
- func Info(msg string, fields ...zap.Field)
- func InfoCtx(ctx context.Context, msg string, fields ...zap.Field)
- func InfoWithRedactedFields(msg string, fields map[string]interface{})
- func Infof(format string, args ...interface{})
- func InfofCtx(ctx context.Context, format string, args ...interface{})
- func Init(config *LogConfig, mode string) (err error)
- func InitTimezone(name string)
- func IsSensitiveField(key string) bool
- func IsTraceEnabled() bool
- func LogDirFromFilename(filename string) string
- func Panic(msg string, fields ...zap.Field)
- func PanicCtx(ctx context.Context, msg string, fields ...zap.Field)
- func Panicf(format string, args ...interface{})
- func PrintDebug(args ...any)
- func PrintError(args ...any)
- func PrintFatal(args ...any)
- func PrintInfo(args ...any)
- func PrintWarn(args ...any)
- func PurgeExpiredLogFiles(logDir string, retentionDays int) (removed int, err error)
- func RedactEmail(email string) string
- func RedactField(key string, value interface{}) interface{}
- func RedactFields(fields map[string]interface{}) map[string]interface{}
- func RedactPhone(phone string) string
- func RedactSIPURI(s string) string
- func RedactString(s string) string
- func RedactValue(data string) string
- func RequestIDFromContext(ctx context.Context) string
- func SafeGo(name string, fn func())
- func SetLevel(level string)
- func SetTraceEnabled(enabled bool)
- func Sync()
- func Tracef(format string, args ...any)
- func Warn(msg string, fields ...zap.Field)
- func WarnCtx(ctx context.Context, msg string, fields ...zap.Field)
- func Warnf(format string, args ...interface{})
- func WarnfCtx(ctx context.Context, format string, args ...interface{})
- func WithError(err error) zap.Field
- func WithFields(fields map[string]interface{}) []zap.Field
- func WithRequestID(ctx context.Context, reqID string) context.Context
- func WrapCoreWithReqIDPrefix(inner zapcore.Core) zapcore.Core
- func ZapReqID(ctx context.Context) zap.Field
- func ZapReqIDString(reqID string) zap.Field
- type LogConfig
- type Logger
Constants ¶
const ( TraceIDKey contextKey = "trace_id" RequestIDKey contextKey = "request_id" UserIDKey contextKey = "user_id" XReqIDKey contextKey = "x-reqid" TenantIDKey contextKey = "tenant_id" CallIDKey contextKey = "call_id" CampaignIDKey contextKey = "campaign_id" )
const ( HeaderXReqID = "X-Reqid" GinCtxReqIDKey = "x-reqid" )
HTTP header and Gin context key for request correlation (aligned with root logger package).
const ( LevelDebug = "debug" LevelInfo = "info" LevelWarn = "warn" LevelError = "error" LevelFatal = "fatal" )
Log level name constants (agentkit/log compatibility).
const DefaultSensitiveFields = "password,passwd,pwd,dsn,secret,token,access_token,refresh_token,api_key,apikey,ssn,phone,email," +
"from_tn,dest_tn,from_user,to_user,caller_user,caller_id,pai,from_number,to_number,caller_number,callee_number,mobile,telephone,tel," +
"from_header,to_header,from_uri,to_uri,sip_from,sip_to," +
"caller_text,agent_text,callee_text,turn_preview,asr_text,llm_text,turn_text,dialog_text,asr,llm"
DefaultSensitiveFields is the comma-separated list of field names the zap core wrapper redacts automatically. Telephony-specific keys are included so that phone numbers (from_tn/dest_tn/from_user/pai/…) and dialog content (caller_text/turn_preview/asr_text/…) are masked before hitting disk.
const DefaultTimezone = constants.DefaultTimezone
DefaultTimezone is used when InitTimezone is not called or the given name is invalid.
const PanicPrefix = "[PANIC]"
PanicPrefix marks recovered panic logs so log-based collectors can report them.
Variables ¶
var DebugContext = func(ctx context.Context, args ...any) { if ContextDefault != nil { ContextDefault.Debug(args...) return } DebugCtx(ctx, sprintArgs(args...)) }
var DebugfContext = func(ctx context.Context, format string, args ...any) { if ContextDefault != nil { ContextDefault.Debugf(format, args...) return } DebugfCtx(ctx, format, args...) }
DebugfContext is an alias of DebugfCtx.
var ErrorContext = func(ctx context.Context, args ...any) { if ContextDefault != nil { ContextDefault.Error(args...) return } ErrorCtx(ctx, sprintArgs(args...)) }
var ErrorfContext = func(ctx context.Context, format string, args ...any) { if ContextDefault != nil { ContextDefault.Errorf(format, args...) return } ErrorfCtx(ctx, format, args...) }
ErrorfContext is an alias of ErrorfCtx.
var FatalContext = func(ctx context.Context, args ...any) { if ContextDefault != nil { ContextDefault.Fatal(args...) return } FatalCtx(ctx, sprintArgs(args...)) }
var FatalfContext = func(ctx context.Context, format string, args ...any) { if ContextDefault != nil { ContextDefault.Fatalf(format, args...) return } FatalfCtx(ctx, format, args...) }
FatalfContext logs a formatted fatal message with context.
var InfoContext = func(ctx context.Context, args ...any) { if ContextDefault != nil { ContextDefault.Info(args...) return } InfoCtx(ctx, sprintArgs(args...)) }
var InfofContext = func(ctx context.Context, format string, args ...any) { if ContextDefault != nil { ContextDefault.Infof(format, args...) return } InfofCtx(ctx, format, args...) }
InfofContext is an alias of InfofCtx.
var (
Lg *zap.Logger
)
var TracefContext = func(ctx context.Context, format string, args ...any) { if !IsTraceEnabled() { return } if ContextDefault != nil { ContextDefault.Debugf("[TRACE] "+format, args...) return } DebugfCtx(ctx, "[TRACE] "+format, args...) }
TracefContext logs a TRACE message with context when enabled.
var WarnContext = func(ctx context.Context, args ...any) { if ContextDefault != nil { ContextDefault.Warn(args...) return } WarnCtx(ctx, sprintArgs(args...)) }
var WarnfContext = func(ctx context.Context, format string, args ...any) { if ContextDefault != nil { ContextDefault.Warnf(format, args...) return } WarnfCtx(ctx, format, args...) }
WarnfContext is an alias of WarnfCtx.
Functions ¶
func Close ¶ added in v0.1.2
func Close()
Close flushes buffered log entries and releases underlying resources (e.g. lumberjack file handles). After Close, the global logger Lg is set to nil and subsequent log calls will use a no-op fallback.
func Debugf ¶
func Debugf(format string, args ...interface{})
Debugf logs at debug level with fmt.Sprintf-style formatting.
func ErrorWithRedactedFields ¶
ErrorWithRedactedFields logs error with sensitive fields redacted.
func Errorf ¶
func Errorf(format string, args ...interface{})
Errorf logs at error level with fmt.Sprintf-style formatting.
func Fatalf ¶
func Fatalf(format string, args ...interface{})
Fatalf logs at fatal level with fmt.Sprintf-style formatting.
func GenReqID ¶
func GenReqID() string
GenReqID generates a URL-safe request id (same algorithm as github.com/.../logger at repo root).
func GetDailyLogFilename ¶
GetDailyLogFilename returns the date-segmented log filename.
func Info ¶
Info logs at info level (skips this package frame so caller points to the business call site).
func InfoWithRedactedFields ¶
InfoWithRedactedFields logs info with sensitive fields redacted.
func Infof ¶
func Infof(format string, args ...interface{})
Infof logs at info level with fmt.Sprintf-style formatting.
func InitTimezone ¶
func InitTimezone(name string)
InitTimezone loads the IANA timezone name and sets the package-level timezone. Call once at startup. Unlike modifying time.Local directly, this is safe to call concurrently with time.Now() in background goroutines.
func IsSensitiveField ¶
IsSensitiveField reports whether key is configured as sensitive.
func IsTraceEnabled ¶ added in v0.1.1
func IsTraceEnabled() bool
IsTraceEnabled reports whether trace logging is active.
func LogDirFromFilename ¶
LogDirFromFilename returns the directory containing log files derived from LOG_FILENAME.
func Panicf ¶
func Panicf(format string, args ...interface{})
Panicf logs at panic level with fmt.Sprintf-style formatting.
func PrintFatal ¶ added in v0.1.1
func PrintFatal(args ...any)
PrintFatal logs with fmt.Sprint and exits.
func PrintInfo ¶ added in v0.1.1
func PrintInfo(args ...any)
PrintInfo logs with fmt.Sprint (multi-arg Print-style; avoids clashing with Info(msg, fields...)).
func PurgeExpiredLogFiles ¶
PurgeExpiredLogFiles removes regular files under logDir older than retentionDays.
func RedactField ¶
func RedactField(key string, value interface{}) interface{}
RedactField redacts value when key is a configured sensitive field.
func RedactFields ¶
RedactFields redacts sensitive keys in a map.
func RedactSIPURI ¶
RedactSIPURI masks the user portion of sip:/sips: URIs in s, preserving host/port for debugging. Falls back to generic string redaction when no URI is present.
func RedactValue ¶
RedactValue redacts JSON-like sensitive key/value pairs in a string.
func RequestIDFromContext ¶
RequestIDFromContext reads the request id from context.
func SafeGo ¶
func SafeGo(name string, fn func())
SafeGo runs fn in a new goroutine with panic recovery and structured logging. Returns immediately. name is a short tag identifying the goroutine in logs (e.g. "transfer-dial", "campaign-worker"). Empty name is tolerated but discouraged.
func SetLevel ¶ added in v0.1.1
func SetLevel(level string)
SetLevel sets the runtime log level for the auto-initialized console logger and, when possible, the global Lg core.
func SetTraceEnabled ¶ added in v0.1.1
func SetTraceEnabled(enabled bool)
SetTraceEnabled toggles Tracef / TracefContext.
func Warnf ¶
func Warnf(format string, args ...interface{})
Warnf logs at warn level with fmt.Sprintf-style formatting.
func WithFields ¶
WithFields creates zap.Field slice from a map.
func WithRequestID ¶
WithRequestID stores req id on context for InfoCtx / ErrorCtx and downstream RPC.
func WrapCoreWithReqIDPrefix ¶
WrapCoreWithReqIDPrefix returns a Core that strips request-id fields and prepends "[reqid:<value>] " to each entry's message. inner must be non-nil; nil short-circuits to inner to avoid hiding configuration mistakes.
func ZapReqIDString ¶
ZapReqIDString returns a zap field for a raw request id string.
Types ¶
type LogConfig ¶
type LogConfig struct {
Level string `mapstructure:"level"`
Filename string `mapstructure:"filename"`
MaxSize int `mapstructure:"max_size"`
MaxAge int `mapstructure:"max_age"` // lumberjack rotation age (days)
RetentionDays int `mapstructure:"retention_days"` // purge files under logs dir (from LOG_RETENTION_DAYS)
MaxBackups int `mapstructure:"max_backups"`
Daily bool `mapstructure:"daily"`
SensitiveFields string `mapstructure:"sensitive_fields"` // comma-separated; from LOG_SENSITIVE_FIELDS
}
type Logger ¶ added in v0.1.1
type Logger interface {
Debug(args ...any)
Debugf(format string, args ...any)
Info(args ...any)
Infof(format string, args ...any)
Warn(args ...any)
Warnf(format string, args ...any)
Error(args ...any)
Errorf(format string, args ...any)
Fatal(args ...any)
Fatalf(format string, args ...any)
}
Logger is the printf-style interface used by injectable defaults (tests).