logger

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 18, 2026 License: MIT Imports: 15 Imported by: 0

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

View Source
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"
)
View Source
const (
	HeaderXReqID   = "X-Reqid"
	GinCtxReqIDKey = "x-reqid"
)

HTTP header and Gin context key for request correlation (aligned with root logger package).

View Source
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.

View Source
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

View Source
var (
	Lg *zap.Logger
)

Functions

func Debug

func Debug(msg string, fields ...zap.Field)

Debug logs at debug level.

func DebugCtx

func DebugCtx(ctx context.Context, msg string, fields ...zap.Field)

DebugCtx logs at debug level with context-derived fields.

func Debugf

func Debugf(format string, args ...interface{})

Debugf logs at debug level with fmt.Sprintf-style formatting.

func DebugfCtx

func DebugfCtx(ctx context.Context, format string, args ...interface{})

DebugfCtx logs at debug level with context and fmt.Sprintf-style formatting.

func Error

func Error(msg string, fields ...zap.Field)

Error logs at error level.

func ErrorCtx

func ErrorCtx(ctx context.Context, msg string, fields ...zap.Field)

ErrorCtx logs at error level with context-derived fields.

func ErrorWithRedactedFields

func ErrorWithRedactedFields(msg string, fields map[string]interface{})

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 ErrorfCtx

func ErrorfCtx(ctx context.Context, format string, args ...interface{})

ErrorfCtx logs at error level with context and fmt.Sprintf-style formatting.

func Fatal

func Fatal(msg string, fields ...zap.Field)

Fatal logs at fatal level and exits.

func FatalCtx

func FatalCtx(ctx context.Context, msg string, fields ...zap.Field)

FatalCtx logs at fatal level with context-derived fields and exits.

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

func GetDailyLogFilename(baseFilename string) string

GetDailyLogFilename returns the date-segmented log filename.

func Info

func Info(msg string, fields ...zap.Field)

Info logs at info level (skips this package frame so caller points to the business call site).

func InfoCtx

func InfoCtx(ctx context.Context, msg string, fields ...zap.Field)

InfoCtx logs at info level with context-derived fields.

func InfoWithRedactedFields

func InfoWithRedactedFields(msg string, fields map[string]interface{})

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 InfofCtx

func InfofCtx(ctx context.Context, format string, args ...interface{})

InfofCtx logs at info level with context and fmt.Sprintf-style formatting.

func Init

func Init(config *LogConfig, mode string) (err error)

Init initializes the global logger once using sync.Once.

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

func IsSensitiveField(key string) bool

IsSensitiveField reports whether key is configured as sensitive.

func LogDirFromFilename

func LogDirFromFilename(filename string) string

LogDirFromFilename returns the directory containing log files derived from LOG_FILENAME.

func Panic

func Panic(msg string, fields ...zap.Field)

Panic logs at panic level and panics.

func PanicCtx

func PanicCtx(ctx context.Context, msg string, fields ...zap.Field)

PanicCtx logs at panic level with context-derived fields and panics.

func Panicf

func Panicf(format string, args ...interface{})

Panicf logs at panic level with fmt.Sprintf-style formatting.

func PurgeExpiredLogFiles

func PurgeExpiredLogFiles(logDir string, retentionDays int) (removed int, err error)

PurgeExpiredLogFiles removes regular files under logDir older than retentionDays.

func RedactEmail

func RedactEmail(email string) string

RedactEmail redacts an email address.

func RedactField

func RedactField(key string, value interface{}) interface{}

RedactField redacts value when key is a configured sensitive field.

func RedactFields

func RedactFields(fields map[string]interface{}) map[string]interface{}

RedactFields redacts sensitive keys in a map.

func RedactPhone

func RedactPhone(phone string) string

RedactPhone redacts a phone number.

func RedactSIPURI

func RedactSIPURI(s string) string

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 RedactString

func RedactString(s string) string

RedactString redacts a generic string value.

func RedactValue

func RedactValue(data string) string

RedactValue redacts JSON-like sensitive key/value pairs in a string.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

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 Sync

func Sync()

Sync flushes buffered log entries.

func Warn

func Warn(msg string, fields ...zap.Field)

Warn logs at warn level.

func WarnCtx

func WarnCtx(ctx context.Context, msg string, fields ...zap.Field)

WarnCtx logs at warn level with context-derived fields.

func Warnf

func Warnf(format string, args ...interface{})

Warnf logs at warn level with fmt.Sprintf-style formatting.

func WarnfCtx

func WarnfCtx(ctx context.Context, format string, args ...interface{})

WarnfCtx logs at warn level with context and fmt.Sprintf-style formatting.

func WithError

func WithError(err error) zap.Field

WithError creates an error zap.Field.

func WithFields

func WithFields(fields map[string]interface{}) []zap.Field

WithFields creates zap.Field slice from a map.

func WithRequestID

func WithRequestID(ctx context.Context, reqID string) context.Context

WithRequestID stores req id on context for InfoCtx / ErrorCtx and downstream RPC.

func WrapCoreWithReqIDPrefix

func WrapCoreWithReqIDPrefix(inner zapcore.Core) zapcore.Core

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 ZapReqID

func ZapReqID(ctx context.Context) zap.Field

ZapReqID returns a zap field for x-reqid when present on context.

func ZapReqIDString

func ZapReqIDString(reqID string) zap.Field

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
}

Directories

Path Synopsis
gin module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL