Documentation
¶
Overview ¶
Package log provides a log for the framework and applications.
Example ¶
package main import ( "trpc.group/trpc-go/trpc-go/log" ) func main() { l := log.NewZapLog([]log.OutputConfig{ { Writer: "console", Level: "debug", Formatter: "console", FormatConfig: log.FormatConfig{TimeFmt: "xxx"}, }, }) const defaultLoggerName = "default" oldDefaultLogger := log.GetDefaultLogger() log.Register(defaultLoggerName, l) defer func() { log.Register(defaultLoggerName, oldDefaultLogger) }() l = log.With(log.Field{Key: "tRPC-Go", Value: "log"}) l.Trace("hello world") l.Debug("hello world") l.Info("hello world") l.Warn("hello world") l.Error("hello world") l.Tracef("hello world") l.Debugf("hello world") l.Infof("hello world") l.Warnf("hello world") l.Errorf("hello world") }
Output: xxx DEBUG log/example_test.go:35 hello world {"tRPC-Go": "log"} xxx DEBUG log/example_test.go:36 hello world {"tRPC-Go": "log"} xxx INFO log/example_test.go:37 hello world {"tRPC-Go": "log"} xxx WARN log/example_test.go:38 hello world {"tRPC-Go": "log"} xxx ERROR log/example_test.go:39 hello world {"tRPC-Go": "log"} xxx DEBUG log/example_test.go:40 hello world {"tRPC-Go": "log"} xxx DEBUG log/example_test.go:41 hello world {"tRPC-Go": "log"} xxx INFO log/example_test.go:42 hello world {"tRPC-Go": "log"} xxx WARN log/example_test.go:43 hello world {"tRPC-Go": "log"} xxx ERROR log/example_test.go:44 hello world {"tRPC-Go": "log"}
Index ¶
- Constants
- Variables
- func CustomTimeFormat(t time.Time, format string) string
- func Debug(args ...interface{})
- func DebugContext(ctx context.Context, args ...interface{})
- func DebugContextf(ctx context.Context, format string, args ...interface{})
- func Debugf(format string, args ...interface{})
- func DefaultTimeFormat(t time.Time) []byte
- func EnableTrace()
- func Error(args ...interface{})
- func ErrorContext(ctx context.Context, args ...interface{})
- func ErrorContextf(ctx context.Context, format string, args ...interface{})
- func Errorf(format string, args ...interface{})
- func Fatal(args ...interface{})
- func FatalContext(ctx context.Context, args ...interface{})
- func FatalContextf(ctx context.Context, format string, args ...interface{})
- func Fatalf(format string, args ...interface{})
- func GetLogEncoderKey(defKey, key string) string
- func GetWriter(name string) plugin.Factory
- func Info(args ...interface{})
- func InfoContext(ctx context.Context, args ...interface{})
- func InfoContextf(ctx context.Context, format string, args ...interface{})
- func Infof(format string, args ...interface{})
- func NewTimeEncoder(format string) zapcore.TimeEncoder
- func RedirectStdLog(logger Logger) (func(), error)
- func RedirectStdLogAt(logger Logger, level zapcore.Level) (func(), error)
- func Register(name string, logger Logger)
- func RegisterFormatEncoder(formatName string, newFormatEncoder NewFormatEncoder)
- func RegisterWriter(name string, writer plugin.Factory)
- func SetLevel(output string, level Level)
- func SetLogger(logger Logger)
- func Sync()
- func Trace(args ...interface{})
- func TraceContext(ctx context.Context, args ...interface{})
- func TraceContextf(ctx context.Context, format string, args ...interface{})
- func Tracef(format string, args ...interface{})
- func Warn(args ...interface{})
- func WarnContext(ctx context.Context, args ...interface{})
- func WarnContextf(ctx context.Context, format string, args ...interface{})
- func Warnf(format string, args ...interface{})
- func WithContextFields(ctx context.Context, fields ...string) context.Context
- type Config
- type ConsoleWriterFactory
- type Decoder
- type Factory
- type Field
- type FileWriterFactory
- type FormatConfig
- type Level
- type Logger
- type LoggerOption
- type LoggerOptions
- type NewFormatEncoder
- type Option
- type OptionLogger
- type OutputConfig
- type TimeUnit
- type WriteConfig
- type WriteMode
Examples ¶
Constants ¶
const ( OutputConsole = "console" OutputFile = "file" )
output name, default support console and file.
const ( // WriteSync writes synchronously. WriteSync = 1 // WriteAsync writes asynchronously. WriteAsync = 2 // WriteFast writes fast(may drop logs asynchronously). WriteFast = 3 )
const ( // RollBySize rolls logs by file size. RollBySize = "size" // RollByTime rolls logs by time. RollByTime = "time" )
By which log rolls.
const ( // TimeFormatMinute is accurate to the minute. TimeFormatMinute = "%Y%m%d%H%M" // TimeFormatHour is accurate to the hour. TimeFormatHour = "%Y%m%d%H" // TimeFormatDay is accurate to the day. TimeFormatDay = "%Y%m%d" // TimeFormatMonth is accurate to the month. TimeFormatMonth = "%Y%m" // TimeFormatYear is accurate to the year. TimeFormatYear = "%Y" )
Some common used time formats.
const ( // Minute splits by the minute. Minute = "minute" // Hour splits by the hour. Hour = "hour" // Day splits by the day. Day = "day" // Month splits by the month. Month = "month" // Year splits by the year. Year = "year" )
const ( ConsoleZapCore = "console" FileZapCore = "file" )
Some ZapCore constants.
Variables ¶
var ( // DefaultConsoleWriterFactory is the default console output implementation. DefaultConsoleWriterFactory = &ConsoleWriterFactory{} // DefaultFileWriterFactory is the default file output implementation. DefaultFileWriterFactory = &FileWriterFactory{} )
var LevelNames = map[string]Level{ "trace": LevelTrace, "debug": LevelDebug, "info": LevelInfo, "warn": LevelWarn, "error": LevelError, "fatal": LevelFatal, }
LevelNames is the map from string to log level.
var LevelStrings = map[Level]string{ LevelTrace: "trace", LevelDebug: "debug", LevelInfo: "info", LevelWarn: "warn", LevelError: "error", LevelFatal: "fatal", }
LevelStrings is the map from log level to its string representation.
var Levels = map[string]zapcore.Level{ "": zapcore.DebugLevel, "trace": zapcore.DebugLevel, "debug": zapcore.DebugLevel, "info": zapcore.InfoLevel, "warn": zapcore.WarnLevel, "error": zapcore.ErrorLevel, "fatal": zapcore.FatalLevel, }
Levels is the map from string to zapcore.Level.
Functions ¶
func CustomTimeFormat ¶
CustomTimeFormat customize time format. Deprecated: Use https://pkg.go.dev/time#Time.Format instead.
func Debug ¶
func Debug(args ...interface{})
Debug logs to DEBUG log. Arguments are handled in the manner of fmt.Println.
func DebugContext ¶
DebugContext logs to DEBUG log. Arguments are handled in the manner of fmt.Println.
func DebugContextf ¶
DebugContextf logs to DEBUG log. Arguments are handled in the manner of fmt.Printf.
func Debugf ¶
func Debugf(format string, args ...interface{})
Debugf logs to DEBUG log. Arguments are handled in the manner of fmt.Printf.
func DefaultTimeFormat ¶
DefaultTimeFormat returns the default time format "2006-01-02 15:04:05.000". Deprecated: Use https://pkg.go.dev/time#Time.AppendFormat instead.
func Error ¶
func Error(args ...interface{})
Error logs to ERROR log. Arguments are handled in the manner of fmt.Println.
func ErrorContext ¶
ErrorContext logs to ERROR log. Arguments are handled in the manner of fmt.Println.
func ErrorContextf ¶
ErrorContextf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.
func Errorf ¶
func Errorf(format string, args ...interface{})
Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.
func Fatal ¶
func Fatal(args ...interface{})
Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Println. All Fatal logs will exit by calling os.Exit(1). Implementations may also call os.Exit() with a non-zero exit code.
func FatalContext ¶
FatalContext logs to ERROR log. Arguments are handled in the manner of fmt.Println. All Fatal logs will exit by calling os.Exit(1). Implementations may also call os.Exit() with a non-zero exit code.
func FatalContextf ¶
FatalContextf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.
func Fatalf ¶
func Fatalf(format string, args ...interface{})
Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.
func GetLogEncoderKey ¶
GetLogEncoderKey gets user defined log output name, uses defKey if empty.
func Info ¶
func Info(args ...interface{})
Info logs to INFO log. Arguments are handled in the manner of fmt.Println.
func InfoContext ¶
InfoContext logs to INFO log. Arguments are handled in the manner of fmt.Println.
func InfoContextf ¶
InfoContextf logs to INFO log. Arguments are handled in the manner of fmt.Printf.
func Infof ¶
func Infof(format string, args ...interface{})
Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf.
func NewTimeEncoder ¶
func NewTimeEncoder(format string) zapcore.TimeEncoder
NewTimeEncoder creates a time format encoder.
func RedirectStdLog ¶
RedirectStdLog redirects std log to trpc logger as log level INFO. After redirection, log flag is zero, the prefix is empty. The returned function may be used to recover log flag and prefix, and redirect output to os.Stderr.
func RedirectStdLogAt ¶
RedirectStdLogAt redirects std log to trpc logger with a specific level. After redirection, log flag is zero, the prefix is empty. The returned function may be used to recover log flag and prefix, and redirect output to os.Stderr.
func RegisterFormatEncoder ¶ added in v1.0.3
func RegisterFormatEncoder(formatName string, newFormatEncoder NewFormatEncoder)
RegisterFormatEncoder registers a NewFormatEncoder with the specified formatName key. The existing formats include "console" and "json", but you can override these format encoders or provide a new custom one.
func RegisterWriter ¶
RegisterWriter registers log output writer. Writer may have multiple implementations.
func Trace ¶
func Trace(args ...interface{})
Trace logs to TRACE log. Arguments are handled in the manner of fmt.Println.
func TraceContext ¶
TraceContext logs to TRACE log. Arguments are handled in the manner of fmt.Println.
func TraceContextf ¶
TraceContextf logs to TRACE log. Arguments are handled in the manner of fmt.Printf.
func Tracef ¶
func Tracef(format string, args ...interface{})
Tracef logs to TRACE log. Arguments are handled in the manner of fmt.Printf.
func Warn ¶
func Warn(args ...interface{})
Warn logs to WARNING log. Arguments are handled in the manner of fmt.Println.
func WarnContext ¶
WarnContext logs to WARNING log. Arguments are handled in the manner of fmt.Println.
func WarnContextf ¶
WarnContextf logs to WARNING log. Arguments are handled in the manner of fmt.Printf.
Types ¶
type Config ¶
type Config []OutputConfig
Config is the log config. Each log may have multiple outputs.
type ConsoleWriterFactory ¶
type ConsoleWriterFactory struct { }
ConsoleWriterFactory is the console writer instance.
func (*ConsoleWriterFactory) Setup ¶
func (f *ConsoleWriterFactory) Setup(name string, dec plugin.Decoder) error
Setup starts, loads and registers console output writer.
func (*ConsoleWriterFactory) Type ¶
func (f *ConsoleWriterFactory) Type() string
Type returns the log plugin type.
type Decoder ¶
type Decoder struct { OutputConfig *OutputConfig Core zapcore.Core ZapLevel zap.AtomicLevel }
Decoder decodes the log.
type Factory ¶
type Factory struct{}
Factory is the log plugin factory. When server start, the configuration is feed to Factory to generate a log instance.
type Field ¶
type Field struct { Key string Value interface{} }
Field is the user defined log field.
type FileWriterFactory ¶
type FileWriterFactory struct { }
FileWriterFactory is the file writer instance Factory.
func (*FileWriterFactory) Setup ¶
func (f *FileWriterFactory) Setup(name string, dec plugin.Decoder) error
Setup starts, loads and register file output writer.
func (*FileWriterFactory) Type ¶
func (f *FileWriterFactory) Type() string
Type returns log file type.
type FormatConfig ¶
type FormatConfig struct { // TimeFmt is the time format of log output, default as "2006-01-02 15:04:05.000" on empty. TimeFmt string `yaml:"time_fmt"` // TimeKey is the time key of log output, default as "T". TimeKey string `yaml:"time_key"` // LevelKey is the level key of log output, default as "L". LevelKey string `yaml:"level_key"` // NameKey is the name key of log output, default as "N". NameKey string `yaml:"name_key"` // CallerKey is the caller key of log output, default as "C". CallerKey string `yaml:"caller_key"` // FunctionKey is the function key of log output, default as "", which means not to print // function name. FunctionKey string `yaml:"function_key"` // MessageKey is the message key of log output, default as "M". MessageKey string `yaml:"message_key"` // StackTraceKey is the stack trace key of log output, default as "S". StacktraceKey string `yaml:"stacktrace_key"` }
FormatConfig is the log format config.
type Logger ¶
type Logger interface { // Trace logs to TRACE log. Arguments are handled in the manner of fmt.Println. Trace(args ...interface{}) // Tracef logs to TRACE log. Arguments are handled in the manner of fmt.Printf. Tracef(format string, args ...interface{}) // Debug logs to DEBUG log. Arguments are handled in the manner of fmt.Println. Debug(args ...interface{}) // Debugf logs to DEBUG log. Arguments are handled in the manner of fmt.Printf. Debugf(format string, args ...interface{}) // Info logs to INFO log. Arguments are handled in the manner of fmt.Println. Info(args ...interface{}) // Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf. Infof(format string, args ...interface{}) // Warn logs to WARNING log. Arguments are handled in the manner of fmt.Println. Warn(args ...interface{}) // Warnf logs to WARNING log. Arguments are handled in the manner of fmt.Printf. Warnf(format string, args ...interface{}) // Error logs to ERROR log. Arguments are handled in the manner of fmt.Println. Error(args ...interface{}) // Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. Errorf(format string, args ...interface{}) // Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Println. // All Fatal logs will exit by calling os.Exit(1). // Implementations may also call os.Exit() with a non-zero exit code. Fatal(args ...interface{}) // Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. Fatalf(format string, args ...interface{}) // Sync calls the underlying Core's Sync method, flushing any buffered log entries. // Applications should take care to call Sync before exiting. Sync() error // SetLevel sets the output log level. SetLevel(output string, level Level) // GetLevel gets the output log level. GetLevel(output string) Level // With adds user defined fields to Logger. Fields support multiple values. With(fields ...Field) Logger }
Logger is the underlying logging work for tRPC framework.
func Get ¶
Get returns the Logger implementation by log name. log.Debug use DefaultLogger to print logs. You may also use log.Get("name").Debug.
func GetDefaultLogger ¶
func GetDefaultLogger() Logger
GetDefaultLogger gets the default Logger. To configure it, set key in configuration file to default. The console output is the default value.
func NewZapLogWithCallerSkip ¶
NewZapLogWithCallerSkip creates a trpc default Logger from zap.
type LoggerOptions ¶
LoggerOptions is the log options.
type NewFormatEncoder ¶ added in v1.0.3
type NewFormatEncoder func(zapcore.EncoderConfig) zapcore.Encoder
NewFormatEncoder is the function type for creating a format encoder out of an encoder config.
type Option ¶
type Option func(*options)
Option modifies the options of optionLogger.
func WithAdditionalCallerSkip ¶
WithAdditionalCallerSkip adds additional caller skip.
type OptionLogger ¶
OptionLogger defines logger with additional options.
type OutputConfig ¶
type OutputConfig struct { // Writer is the output of log, such as console or file. Writer string `yaml:"writer"` WriteConfig WriteConfig `yaml:"writer_config"` // Formatter is the format of log, such as console or json. Formatter string `yaml:"formatter"` FormatConfig FormatConfig `yaml:"formatter_config"` // RemoteConfig is the remote config. It's defined by business and should be registered by // third-party modules. RemoteConfig yaml.Node `yaml:"remote_config"` // Level controls the log level, like debug, info or error. Level string `yaml:"level"` // CallerSkip controls the nesting depth of log function. CallerSkip int `yaml:"caller_skip"` // EnableColor determines if the output is colored. The default value is false. EnableColor bool `yaml:"enable_color"` }
OutputConfig is the output config, includes console, file and remote.
type TimeUnit ¶
type TimeUnit string
TimeUnit is the time unit by which files are split, one of minute/hour/day/month/year.
func (TimeUnit) RotationGap ¶
RotationGap returns the time.Duration for time unit. Use one day as the default.
type WriteConfig ¶
type WriteConfig struct { // LogPath is the log path like /usr/local/trpc/log/. LogPath string `yaml:"log_path"` // Filename is the file name like trpc.log. Filename string `yaml:"filename"` // WriteMode is the log write mod. 1: sync, 2: async, 3: fast(maybe dropped), default as 3. WriteMode int `yaml:"write_mode"` // RollType is the log rolling type. Split files by size/time, default by size. RollType string `yaml:"roll_type"` // MaxAge is the max expire times(day). MaxAge int `yaml:"max_age"` // MaxBackups is the max backup files. MaxBackups int `yaml:"max_backups"` // Compress defines whether log should be compressed. Compress bool `yaml:"compress"` // MaxSize is the max size of log file(MB). MaxSize int `yaml:"max_size"` // TimeUnit splits files by time unit, like year/month/hour/minute, default day. // It takes effect only when split by time. TimeUnit TimeUnit `yaml:"time_unit"` }
WriteConfig is the local file config.
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
Package rollwriter provides a high performance rolling file log.
|
Package rollwriter provides a high performance rolling file log. |