logger

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 15 Imported by: 0

README

logger

Structured logging for ling-base, built on zap with lumberjack rotation, colored console output, sensitive field redaction, request ID tracking, and panic-safe goroutines.

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 (passwords, tokens, phone numbers, SIP URIs, emails)
  • Request ID generation, context binding, and message prefixing
  • Context-aware logging helpers (InfoCtx, ErrorCtx, ...)
  • SafeGo for panic-safe background goroutines
  • Log retention purge for expired files

Key types

  • LogConfig -- logger configuration (level, filename, max size/age/backups, retention, sensitive fields)

Key functions

  • InitTimezone(name) -- set the package-level timezone (call before Init)
  • Init(config, mode) -- initialize the global zap logger
  • Info, Debug, Warn, Error, Fatal -- structured logging
  • InfoCtx, ErrorCtx, ... -- context-aware variants with request ID
  • GenReqID() -- generate URL-safe request ID
  • WithRequestID(ctx, reqID), RequestIDFromContext(ctx), ZapReqID(ctx)
  • SafeGo(name, fn) -- panic-recovered goroutine launcher
  • PurgeExpiredLogFiles(logDir, retentionDays) -- remove old log files
  • RedactString, RedactEmail, RedactPhone, RedactSIPURI, RedactField

Quick start

import "github.com/LingByte/ling-base/common/logger"

logger.InitTimezone("Asia/Shanghai")
_ = logger.Init(&logger.LogConfig{
    Level:    "info",
    Filename: "./logs/app.log",
    MaxSize:  100,
    MaxAge:   30,
    Daily:    true,
}, "dev")

logger.Info("server started", zap.String("addr", ":8080"))
logger.SafeGo("worker", func() { runWorker() })

License

MIT

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 (
	LevelDebug = "debug"
	LevelInfo  = "info"
	LevelWarn  = "warn"
	LevelError = "error"
	LevelFatal = "fatal"
)

Log level name constants (agentkit/log compatibility).

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.

View Source
const PanicPrefix = "[PANIC]"

PanicPrefix marks recovered panic logs so log-based collectors can report them.

Variables

View Source
var DebugContext = func(ctx context.Context, args ...any) {
	if ContextDefault != nil {
		ContextDefault.Debug(args...)
		return
	}
	DebugCtx(ctx, sprintArgs(args...))
}
View Source
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.

View Source
var ErrorContext = func(ctx context.Context, args ...any) {
	if ContextDefault != nil {
		ContextDefault.Error(args...)
		return
	}
	ErrorCtx(ctx, sprintArgs(args...))
}
View Source
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.

View Source
var FatalContext = func(ctx context.Context, args ...any) {
	if ContextDefault != nil {
		ContextDefault.Fatal(args...)
		return
	}
	FatalCtx(ctx, sprintArgs(args...))
}
View Source
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.

View Source
var InfoContext = func(ctx context.Context, args ...any) {
	if ContextDefault != nil {
		ContextDefault.Info(args...)
		return
	}
	InfoCtx(ctx, sprintArgs(args...))
}
View Source
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.

View Source
var (
	Lg *zap.Logger
)
View Source
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.

View Source
var WarnContext = func(ctx context.Context, args ...any) {
	if ContextDefault != nil {
		ContextDefault.Warn(args...)
		return
	}
	WarnCtx(ctx, sprintArgs(args...))
}
View Source
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 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 FatalfCtx added in v0.1.1

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

FatalfCtx logs at fatal level with context and 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 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

func IsSensitiveField(key string) bool

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

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 PrintDebug added in v0.1.1

func PrintDebug(args ...any)

PrintDebug logs with fmt.Sprint.

func PrintError added in v0.1.1

func PrintError(args ...any)

PrintError logs with fmt.Sprint.

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 PrintWarn added in v0.1.1

func PrintWarn(args ...any)

PrintWarn logs with fmt.Sprint.

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 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 Sync

func Sync()

Sync flushes buffered log entries.

func Tracef added in v0.1.1

func Tracef(format string, args ...any)

Tracef logs at debug with a [TRACE] prefix when enabled.

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
}

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).

var (

	// Default, when non-nil, receives printf-style package helpers (tests inject mocks).
	Default Logger
	// ContextDefault is used by *Context helpers when set.
	ContextDefault Logger
)

Directories

Path Synopsis
gin module

Jump to

Keyboard shortcuts

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