Help us shape the future of Go! Take the 2026 Go Developer Survey

logger

package
v1.21.2 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: GPL-3.0 Imports: 26 Imported by: 0

README

logger configurations

type LogConf struct {
	ServiceName         string              
	Mode                string              
	Encoding            string              
	TimeFormat          string              
	Path                string              
	Level               string              
	Compress            bool                
	KeepDays            int                 
	StackCooldownMillis int                 
	MaxBackups          int                 
	MaxSize             int                 
	Rotation            string              
}
  • ServiceName: set the service name, optional. on volume mode, the name is used to generate the log files. Within rest/zrpc services, the name will be set to the name of rest or zrpc automatically.
  • Mode: the mode to output the logs, default is console.
    • console mode writes the logs to stdout/stderr.
    • file mode writes the logs to the files specified by Path.
    • volume mode is used in docker, to write logs into mounted volumes.
  • Encoding: indicates how to encode the logs, default is json.
    • json mode writes the logs in json format.
    • plain mode writes the logs with plain text, with terminal color enabled.
  • TimeFormat: customize the time format, optional. Default is 2006-01-02T15:04:05.000Z07:00.
  • Path: set the log path, default to logs.
  • Level: the logging level to filter logs. Default is info.
    • info, all logs are written.
    • error, info logs are suppressed.
    • severe, info and error logs are suppressed, only severe logs are written.
  • Compress: whether or not to compress log files, only works with file mode.
  • KeepDays: how many days that the log files are kept, after the given days, the outdated files will be deleted automatically. It has no effect on console mode.
  • StackCooldownMillis: how many milliseconds to rewrite stacktrace again. It’s used to avoid stacktrace flooding.
  • MaxBackups: represents how many backup log files will be kept. 0 means all files will be kept forever. Only take effect when Rotation is size. NOTE: the level of option KeepDays will be higher. Even though MaxBackups sets 0, log files will still be removed if the KeepDays limitation is reached.
  • MaxSize: represents how much space the writing log file takes up. 0 means no limit. The unit is MB. Only take effect when Rotation is size.
  • Rotation: represents the type of log rotation rule. Default is daily.
    • daily rotate the logs by day.
    • size rotate the logs by size of logs.

Logging methods

type Logger interface {
	// Debug logs a message at debug level.
	Debug(...any)
	// Debugf logs a message at debug level.
	Debugf(string, ...any)
	// Debugw logs a message at debug level.
	Debugw(string, ...LogField)
	// Error logs a message at error level.
	Error(...any)
	// Errorf logs a message at error level.
	Errorf(string, ...any)
	// Errorw logs a message at error level.
	Errorw(string, ...LogField)
	// Info logs a message at info level.
	Info(...any)
	// Infof logs a message at info level.
	Infof(string, ...any)
	// Infow logs a message at info level.
	Infow(string, ...LogField)
	// Sloww logs a message at slow level.
	Sloww(string, ...LogField)
	// WithCallerSkip returns a new logger with the given caller skip.
	WithCallerSkip(skip int) Logger
	// WithDuration returns a new logger with the given duration.
	WithDuration(d time.Duration) Logger
}
  • logger.WithContext(ctx): returns a Logger that writes the trace and span ids of ctx and the fields logger.ContextWithFields stored in it into every entry.
  • Debug, Error, Info: write any kind of messages into logs, like fmt.Sprint(…); LogField arguments become fields.
  • Debugf, Errorf, Infof: write messages with given format into logs.
  • Debugw, Errorw, Infow, Sloww: write the string message with given key:value fields.
  • WithCallerSkip: skip more stack frames when reporting the caller, for logging helpers.
  • WithDuration: write elapsed duration into the log messages, with key duration.

Write the logs to specific stores

logger defines two functions to let you write logs into any store.

  • logger.NewWriter(w io.Writer)
  • logger.SetWriter(writer logger.Writer)

Filtering sensitive fields

Entries are redacted before they are written. A field whose key names a credential or a personal datum (for example token, password, email, phone) is written as [REDACTED], and JWTs, bot tokens, email addresses, bearer tokens and secret query parameters are masked inside messages and field values. logger.RiskField is the only way to log the client IP and the user agent, which the risk-control audit needs.

Documentation

Overview

Package logger is the process log. Entries are leveled, carry structured fields and are written as JSON or plain text to the console or to rotated files (access, error and slow), with credentials and personal data redacted before they are written. Code on a request or task path logs through WithContext(ctx), so each entry carries the trace and span of the request that caused it; GormLogger reports failed and slow SQL through the same output.

Index

Constants

View Source
const (
	// DebugLevel logs everything
	DebugLevel uint32 = iota
	// InfoLevel does not include debugs
	InfoLevel
	// ErrorLevel includes errors, slows, stacks
	ErrorLevel
	// SevereLevel, the "severe" configuration level, is above every level
	// the server writes, so it silences the log.
	SevereLevel
)
View Source
const RedactedValue = "[REDACTED]"

RedactedValue replaces a redacted field value or text in the log.

View Source
const TAG = "[GORM]"

TAG prefixes the messages GormLogger writes.

Variables

View Source
var (
	// ErrLogPathNotSet is an error that indicates the log path is not set.
	ErrLogPathNotSet = errors.New("log path must be set")
	// ErrLogServiceNameNotSet is an error that indicates that the service name is not set.
	ErrLogServiceNameNotSet = errors.New("log service name must be set")
)
View Source
var (
	// ErrLogFileClosed is an error that indicates the log file is already closed.
	ErrLogFileClosed = errors.New("error: log file closed")
)

Functions

func Close

func Close() error

Close flushes and closes the logging output; entries logged afterwards go to the console.

func ContextWithFields

func ContextWithFields(ctx context.Context, fields ...LogField) context.Context

ContextWithFields returns a new context with the given fields.

func ContextWithRequestMetadata added in v1.20.0

func ContextWithRequestMetadata(ctx context.Context, metadata requestmeta.Metadata) context.Context

ContextWithRequestMetadata adds explicitly authorized risk metadata to all process logs emitted with this context. Credentials, bodies and other personal fields remain governed by the normal redaction policy.

func Debug

func Debug(v ...any)

Debug writes v into access log.

func Disable

func Disable()

Disable disables the logging.

func Error

func Error(v ...any)

Error writes v into error log.

func Errorf

func Errorf(format string, v ...any)

Errorf writes v with format into error log.

func Errorw

func Errorw(msg string, fields ...LogField)

Errorw writes msg along with fields into the error log.

func Info

func Info(v ...any)

Info writes v into access log.

func Infof

func Infof(format string, v ...any)

Infof writes v with format into access log.

func Infow

func Infow(msg string, fields ...LogField)

Infow writes msg along with fields into the access log.

func ReadLastNLogLines added in v1.19.0

func ReadLastNLogLines(path string, n int) ([]string, error)

ReadLastNLogLines returns the last n entries of each log file in path, the directory of the file output, for the administrators' log view. A missing file is skipped; an error is returned only when no log file is readable, as when the logs go to the console.

func SetUp

func SetUp(c LogConf) (err error)

SetUp configures the logger from c. Only the first call takes effect; later calls change nothing and return nil, so the process keeps the output it logged to first.

func SetWriter

func SetWriter(w Writer)

SetWriter sets the logging writer. It can be used to customize the logging.

Types

type DailyRotateRule

type DailyRotateRule struct {
	// contains filtered or unexported fields
}

A DailyRotateRule is a rule to daily rotate the log files.

func (*DailyRotateRule) BackupFileName

func (r *DailyRotateRule) BackupFileName() string

BackupFileName returns the backup filename on rotating.

func (*DailyRotateRule) MarkRotated

func (r *DailyRotateRule) MarkRotated()

MarkRotated marks the rotated time of r to be the current time.

func (*DailyRotateRule) OutdatedFiles

func (r *DailyRotateRule) OutdatedFiles() []string

OutdatedFiles returns the files that exceeded the keeping days.

func (*DailyRotateRule) ShallRotate

func (r *DailyRotateRule) ShallRotate(_ int64) bool

ShallRotate checks if the file should be rotated.

type GormLogger

type GormLogger struct {
	// SlowThreshold is the duration from which a query is logged as slow;
	// zero means one second.
	SlowThreshold time.Duration
}

GormLogger is GORM's logger for the database connections. It writes only failed and slow queries, and of a query only its operation and row count: the statement text can carry the values of personal columns.

func (*GormLogger) Error

func (l *GormLogger) Error(ctx context.Context, str string, args ...any)

func (*GormLogger) Info

func (l *GormLogger) Info(ctx context.Context, str string, args ...any)

Info, Warn and Error log that GORM reported something, without the message, which can carry query values.

func (*GormLogger) LogMode

LogMode keeps the process log level: GORM's level is ignored, and the process level in force is logged instead.

func (*GormLogger) Trace

func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error)

Trace logs a query that failed or took SlowThreshold or longer; a missed lookup (gorm.ErrRecordNotFound) is logged only when it was slow.

func (*GormLogger) Warn

func (l *GormLogger) Warn(ctx context.Context, str string, args ...any)

type LogConf

type LogConf struct {
	// ServiceName represents the service name, default is `PPanel`. In
	// `volume` mode it names the log directory.
	ServiceName string `yaml:"ServiceName" default:"PPanel"`
	// Mode represents the logging mode, default is `file`; an empty mode
	// logs to the console.
	// console: log to console.
	// file: log to file.
	// volume: used in k8s, prepend the hostname to the log file name.
	Mode string `yaml:"Mode" default:"file"`
	// Encoding represents the encoding type, default is `json`.
	// json: json encoding.
	// plain: plain text encoding, typically used in development.
	Encoding string `yaml:"Encoding" default:"json"`
	// TimeFormat represents the time format of log entries, default is
	// `2006-01-02 15:04:05.000`; an empty format keeps
	// `2006-01-02T15:04:05.000Z07:00`.
	TimeFormat string `yaml:"TimeFormat" default:"2006-01-02 15:04:05.000"`
	// Path represents the log file path, default is `logs`.
	Path string `yaml:"Path" default:"logs"`
	// Level represents the log level, default is `info`; an empty level
	// logs everything, debug included.
	Level string `yaml:"Level" default:"info"`
	// MaxContentLength represents the max bytes per textual log value,
	// default is 16384; zero does not truncate.
	MaxContentLength uint32 `yaml:"MaxContentLength" default:"16384"`
	// Compress represents whether to compress the log file, default is `false`.
	Compress bool `yaml:"Compress" default:"false"`
	// Stat is kept so existing configuration files still load; the server
	// writes no statistics logs, so it has no effect.
	Stat bool `yaml:"Stat" default:"true"`
	// KeepDays represents how many days the log files will be kept. Defaults to 30 days.
	// Only take effect when Mode is `file` or `volume`, both work when Rotation is `daily` or `size`.
	KeepDays int `yaml:"KeepDays" default:"30"`
	// StackCooldownMillis represents the cooldown time for stack logging, default is 100ms.
	StackCooldownMillis int `yaml:"StackCooldownMillis" default:"100"`
	// MaxBackups represents how many backup log files will be kept. Defaults to 30.
	// Only take effect when RotationRuleType is `size`.
	// Even though `MaxBackups` sets 0, log files will still be removed
	// if the `KeepDays` limitation is reached.
	MaxBackups int `yaml:"MaxBackups" default:"30"`
	// MaxSize represents how much space the writing log file takes up. Defaults to 100 MB.
	// Only take effect when RotationRuleType is `size`
	MaxSize int `yaml:"MaxSize" default:"100"`
	// Rotation represents the type of log rotation rule. Default is `daily`.
	// daily: daily rotation.
	// size: size limited rotation.
	Rotation string `yaml:"Rotation" default:"daily"`
	// FileTimeFormat represents the time format for file name, default is `2006-01-02T15:04:05.000Z07:00`.
	FileTimeFormat string `yaml:"FileTimeFormat" default:"2006-01-02T15:04:05.000Z07:00"`
}

A LogConf is a logging config. The defaults below are the ones the configuration loader fills in for a missing key (the default tags); a LogConf built in code without them keeps the zero-value behaviour noted where it differs.

type LogField

type LogField struct {
	Key   string
	Value any
	// contains filtered or unexported fields
}

LogField is a key-value pair that will be added to the log entry.

func Field

func Field(key string, value any) LogField

Field returns a LogField for the given key and value.

func RiskField added in v1.20.0

func RiskField(key, value string) LogField

RiskField is the only supported escape hatch for personal metadata in the process log. It is intentionally limited to the two fields explicitly used by the HTTP risk-control audit; every other sensitive key still follows the global redaction policy.

type Logger

type Logger interface {
	// Debug logs a message at debug level.
	Debug(...any)
	// Debugf logs a message at debug level.
	Debugf(string, ...any)
	// Debugw logs a message at debug level.
	Debugw(string, ...LogField)
	// Error logs a message at error level.
	Error(...any)
	// Errorf logs a message at error level.
	Errorf(string, ...any)
	// Errorw logs a message at error level.
	Errorw(string, ...LogField)
	// Info logs a message at info level.
	Info(...any)
	// Infof logs a message at info level.
	Infof(string, ...any)
	// Infow logs a message at info level.
	Infow(string, ...LogField)
	// Sloww logs a message at slow level.
	Sloww(string, ...LogField)
	// WithCallerSkip returns a new logger with the given caller skip.
	WithCallerSkip(skip int) Logger
	// WithDuration returns a new logger with the given duration.
	WithDuration(d time.Duration) Logger
}

A Logger writes entries that carry the trace and span of the context it was made for (see WithContext), the fields stored in that context and the caller's position.

func WithContext

func WithContext(ctx context.Context) Logger

WithContext returns a Logger whose entries carry ctx's trace and span IDs and the fields ContextWithFields stored in ctx, so the entries of one request or task can be found together.

type RotateLogger

type RotateLogger struct {
	// contains filtered or unexported fields
}

A RotateLogger is a Logger that can rotate log files with given rules.

func (*RotateLogger) Close

func (l *RotateLogger) Close() error

Close closes l.

func (*RotateLogger) Write

func (l *RotateLogger) Write(data []byte) (int, error)

type RotateRule

type RotateRule interface {
	BackupFileName() string
	MarkRotated()
	OutdatedFiles() []string
	ShallRotate(size int64) bool
}

A RotateRule interface is used to define the log rotating rules.

type SizeLimitRotateRule

type SizeLimitRotateRule struct {
	DailyRotateRule
	// contains filtered or unexported fields
}

SizeLimitRotateRule a rotation rule that make the log file rotated base on size

func (*SizeLimitRotateRule) BackupFileName

func (r *SizeLimitRotateRule) BackupFileName() string

func (*SizeLimitRotateRule) MarkRotated

func (r *SizeLimitRotateRule) MarkRotated()

func (*SizeLimitRotateRule) OutdatedFiles

func (r *SizeLimitRotateRule) OutdatedFiles() []string

func (*SizeLimitRotateRule) ShallRotate

func (r *SizeLimitRotateRule) ShallRotate(size int64) bool

type Writer

type Writer interface {
	Close() error
	Debug(v any, fields ...LogField)
	Error(v any, fields ...LogField)
	Info(v any, fields ...LogField)
	Slow(v any, fields ...LogField)
	// Stack writes v, a message followed by its call stack, at error
	// level.
	Stack(v any)
}

A Writer is the output the log entries go to; SetWriter installs one. Each method writes one entry of its level, with fields next to v.

func NewWriter

func NewWriter(w io.Writer) Writer

NewWriter returns a Writer that writes the entries of every level to w.

func Reset

func Reset() Writer

Reset removes the output and returns it, so that a test can install its own and restore this one with SetWriter; until an output is set, entries go to a new console output.

Directories

Path Synopsis
Package logtest redirects the process-wide logger output for the length of a test, so a test can assert what was logged or keep expected errors out of the test output.
Package logtest redirects the process-wide logger output for the length of a test, so a test can assert what was logged or keep expected errors out of the test output.

Jump to

Keyboard shortcuts

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