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
- Variables
- func Close() error
- func ContextWithFields(ctx context.Context, fields ...LogField) context.Context
- func ContextWithRequestMetadata(ctx context.Context, metadata requestmeta.Metadata) context.Context
- func Debug(v ...any)
- func Disable()
- func Error(v ...any)
- func Errorf(format string, v ...any)
- func Errorw(msg string, fields ...LogField)
- func Info(v ...any)
- func Infof(format string, v ...any)
- func Infow(msg string, fields ...LogField)
- func ReadLastNLogLines(path string, n int) ([]string, error)
- func SetUp(c LogConf) (err error)
- func SetWriter(w Writer)
- type DailyRotateRule
- type GormLogger
- func (l *GormLogger) Error(ctx context.Context, str string, args ...any)
- func (l *GormLogger) Info(ctx context.Context, str string, args ...any)
- func (l *GormLogger) LogMode(logger.LogLevel) logger.Interface
- func (l *GormLogger) Trace(ctx context.Context, begin time.Time, ...)
- func (l *GormLogger) Warn(ctx context.Context, str string, args ...any)
- type LogConf
- type LogField
- type Logger
- type RotateLogger
- type RotateRule
- type SizeLimitRotateRule
- type Writer
Constants ¶
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 )
const RedactedValue = "[REDACTED]"
RedactedValue replaces a redacted field value or text in the log.
const TAG = "[GORM]"
TAG prefixes the messages GormLogger writes.
Variables ¶
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") )
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 ¶
ContextWithFields returns a new context with the given fields.
func ContextWithRequestMetadata ¶ added in v1.20.0
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 ReadLastNLogLines ¶ added in v1.19.0
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.
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) 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 ¶
func (l *GormLogger) LogMode(logger.LogLevel) logger.Interface
LogMode keeps the process log level: GORM's level is ignored, and the process level in force is logged instead.
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 ¶
LogField is a key-value pair that will be added to the log entry.
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 ¶
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.
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.
Source Files
¶
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. |