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 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 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 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 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 Sync()
- 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
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 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. Mirrors constants.DefaultTimezone to avoid an import cycle if logger is ever split into its own module; keep them in sync.
Variables ¶
var (
Lg *zap.Logger
)
Functions ¶
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 process-global time.Local. Call once at startup before any goroutine calls time.Now(); concurrent writes to time.Local race with time.Now() reads. After this, all time.Now() calls return time in the configured timezone automatically.
func IsSensitiveField ¶
IsSensitiveField reports whether key is configured as sensitive.
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 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 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
}