Logger (Zap)
About 1 mincomponentloggerzap
Overview
logger
is a logger component based on the high-performance logging library zap, providing more convenient log management functions.
Configuration Description
In services created by sponge, the default configuration for the logger component is:
- Log functionality: Enabled, log level is
debug
. - Output target: Standard terminal output
- Log format: console (can be configured as json format)
- Supported features: Log file storage, log rotation, log retention time setting, default is disabled.
Configuration Example
Set the logger
field in the YAML configuration file under the configs
directory:
# logger settings
logger:
level: "info" # Output log level debug, info, warn, error, default is debug
format: "console" # Output format, console or json, default is console
isSave: false # false: output to terminal, true: output to file, default is false
logFileConfig: # Effective when isSave=true
filename: "out.log" # File name, default value out.log
maxSize: 10 # Maximum file size (MB), default value 10MB
maxBackups: 100 # Maximum number of old files to keep, default value 100
maxAge: 30 # Maximum number of days to keep old files, default value 30 days
isCompression: false # Whether to compress/archive old files, default value false
File Log Configuration
To enable file logging functionality:
- Set the relevant parameters in the
logFileConfig
in the configuration file. - Find the
// initializing log
section in the code filecmd/your_server_name/initApp.go
. - Uncomment the following code:
// initializing log
_, err := logger.Init(
logger.WithLevel(cfg.Logger.Level),
logger.WithFormat(cfg.Logger.Format),
logger.WithSave(
cfg.Logger.IsSave,
//logger.WithFileName(cfg.Logger.LogFileConfig.Filename),
//logger.WithFileMaxSize(cfg.Logger.LogFileConfig.MaxSize),
//logger.WithFileMaxBackups(cfg.Logger.LogFileConfig.MaxBackups),
//logger.WithFileMaxAge(cfg.Logger.LogFileConfig.MaxAge),
//logger.WithFileIsCompression(cfg.Logger.LogFileConfig.IsCompression),
),
)
Log Format Description
Default log format features:
- Uses the special marker
<<<<
to indicate the start of a request log. - Uses the special marker
>>>>
to indicate the end of a request log. - The complete request trace logs can be tracked using the same
request_id
. - Start and end markers appear in pairs.
Simplified Log Output
To reduce the amount of log output, you can switch to simple log mode using the following methods:
Web Service:
- Replace
middleware.Logging
withmiddleware.SimpleLog
.
gRPC Service:
- Replace
interceptor.UnaryServerLog
withinterceptor.UnaryServerSimpleLog
. - Replace
interceptor.StreamServerLog
withinterceptor.StreamServerSimpleLog
.