Documentation
¶
Overview ¶
Package log provides a global logger for log.
Example ¶
package main import ( "time" "github.com/pkg/errors" "github.com/sraphs/slog" ) func main() { slog.TimestampFunc = func() time.Time { return time.Date(2001, time.February, 3, 4, 5, 6, 7, time.UTC) } slog.Init(&slog.Config{ Level: "info", Path: "log/app.log", MaxSize: 100, MaxAge: 7, }).WithTimestamp().WithCaller().WithStack() // level log slog.Debug("hello world") slog.Info("hello world") slog.Warn("hello world") slog.Error("hello world") // slog.Fatal("hello world") // format log slog.Debugf("hello %s", "world") slog.Infof("hello %s", "world") slog.Warnf("hello %s", "world") slog.Errorf("hello %s", "world") // slog.Fatalf("hello %s", "world") // log err with stack err := outer() slog.Error(err) slog.Clone().WithFields("foo", "bar").Info("hello world") slog.Info("hello world") // Outputs: // {"level":"info","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:25"} // {"level":"warn","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:26"} // {"level":"error","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:27"} // {"level":"info","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:32"} // {"level":"warn","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:33"} // {"level":"error","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:34"} // {"level":"error","stack":[{"func":"inner","line":"58","source":"example_test.go"},{"func":"middle","line":"62","source":"example_test.go"},{"func":"outer","line":"70","source":"example_test.go"},{"func":"Example","line":"38","source":"example_test.go"},{"func":"runExample","line":"63","source":"run_example.go"},{"func":"runExamples","line":"44","source":"example.go"},{"func":"(*M).Run","line":"1721","source":"testing.go"},{"func":"main","line":"61","source":"_testmain.go"},{"func":"main","line":"250","source":"proc.go"},{"func":"goexit","line":"1571","source":"asm_amd64.s"}],"error":"seems we have an error here","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:39"} // {"level":"info","foo":"bar","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"run_example.go:63"} // {"level":"info","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:43"} } func inner() error { return errors.New("seems we have an error here") } func middle() error { err := inner() if err != nil { return err } return nil } func outer() error { err := middle() if err != nil { return err } return nil }
Output:
Index ¶
- Constants
- Variables
- func Debug(v ...interface{})
- func Debugf(format string, v ...interface{})
- func Error(v ...interface{})
- func Errorf(format string, v ...interface{})
- func Fatal(v ...interface{})
- func Fatalf(format string, v ...interface{})
- func Info(v ...interface{})
- func Infof(format string, v ...interface{})
- func Log(lv Level, v ...interface{})
- func Print(v ...interface{})
- func Printf(format string, v ...interface{})
- func Warn(v ...interface{})
- func Warnf(format string, v ...interface{})
- func WithLogger(ctx context.Context, logger FullLogger) context.Context
- type Config
- func (*Config) Descriptor() ([]byte, []int)deprecated
- func (x *Config) GetLevel() string
- func (x *Config) GetMaxAge() int32
- func (x *Config) GetMaxSize() int32
- func (x *Config) GetPath() string
- func (*Config) ProtoMessage()
- func (x *Config) ProtoReflect() protoreflect.Message
- func (x *Config) Reset()
- func (x *Config) String() string
- type Control
- type FormatLogger
- type FullLogger
- func Clone() FullLogger
- func DefaultLogger() FullLogger
- func FromContext(ctx context.Context) FullLogger
- func Init(c *Config) FullLogger
- func New(c *Config) FullLogger
- func WithCaller() FullLogger
- func WithCallerWithSkipFrameCount(skipFrameCount int) FullLogger
- func WithFields(fields ...interface{}) FullLogger
- func WithStack() FullLogger
- func WithTimestamp() FullLogger
- type Helper
- func (ll *Helper) Clone() FullLogger
- func (ll *Helper) Debug(v ...interface{})
- func (ll *Helper) Debugf(format string, v ...interface{})
- func (ll *Helper) Error(v ...interface{})
- func (ll *Helper) Errorf(format string, v ...interface{})
- func (ll *Helper) Fatal(v ...interface{})
- func (ll *Helper) Fatalf(format string, v ...interface{})
- func (ll *Helper) Info(v ...interface{})
- func (ll *Helper) Infof(format string, v ...interface{})
- func (ll *Helper) Log(lv Level, v ...interface{}) error
- func (ll *Helper) Print(v ...interface{})
- func (ll *Helper) Printf(format string, v ...interface{})
- func (ll *Helper) SetLevel(lv Level) Control
- func (ll *Helper) SetOutput(w io.Writer) Control
- func (ll *Helper) Warn(v ...interface{})
- func (ll *Helper) Warnf(format string, v ...interface{})
- func (ll *Helper) WithCaller() FullLogger
- func (ll *Helper) WithCallerWithSkipFrameCount(skipFrameCount int) FullLogger
- func (ll *Helper) WithFields(fields ...interface{}) FullLogger
- func (ll *Helper) WithStack() FullLogger
- func (ll *Helper) WithTimestamp() FullLogger
- type KLogger
- type Level
- type LevelLogger
Examples ¶
Constants ¶
const ( // LevelDebug is logger debug level. LevelDebug = log.LevelDebug // LevelInfo is logger info level. LevelInfo = log.LevelInfo // LevelWarn is logger warn level. LevelWarn = log.LevelWarn // LevelError is logger error level. LevelError = log.LevelError // LevelFatal is logger fatal level LevelFatal = log.LevelFatal )
Variables ¶
var ( // TimestampFieldName is the field name used for the timestamp field. TimestampFieldName = "ts" // LevelFieldName is the field name used for the level field. LevelFieldName = "level" // LevelTraceValue is the value used for the trace level field. LevelTraceValue = "trace" // LevelDebugValue is the value used for the debug level field. LevelDebugValue = "debug" // LevelInfoValue is the value used for the info level field. LevelInfoValue = "info" // LevelWarnValue is the value used for the warn level field. LevelWarnValue = "warn" // LevelErrorValue is the value used for the error level field. LevelErrorValue = "error" // LevelFatalValue is the value used for the fatal level field. LevelFatalValue = "fatal" // LevelPanicValue is the value used for the panic level field. LevelPanicValue = "panic" // LevelFieldMarshalFunc allows customization of global level field marshaling. LevelFieldMarshalFunc = func(l zlog.Level) string { return l.String() } // MessageFieldName is the field name used for the message field. MessageFieldName = "msg" // ErrorFieldName is the field name used for error fields. ErrorFieldName = "error" // CallerFieldName is the field name used for caller field. CallerFieldName = "caller" // CallerSkipFrameCount is the number of stack frames to skip to find the caller. CallerSkipFrameCount = 2 // CallerMarshalFunc allows customization of global caller marshaling CallerMarshalFunc = func(file string, line int) string { short := file for i := len(file) - 1; i > 0; i-- { if file[i] == '/' { short = file[i+1:] break } } file = short return file + ":" + strconv.Itoa(line) } // ErrorStackFieldName is the field name used for error stacks. ErrorStackFieldName = "stack" // ErrorStackMarshaler extract the stack from err if any. ErrorStackMarshaler = pkgerrors.MarshalStack // ErrorMarshalFunc allows customization of global error marshaling ErrorMarshalFunc = func(err error) interface{} { return err } // InterfaceMarshalFunc allows customization of interface marshaling. // Default: "encoding/json.Marshal" InterfaceMarshalFunc = json.Marshal // TimeFieldFormat defines the time format of the Time field type. If set to // TimeFormatUnix, TimeFormatUnixMs or TimeFormatUnixMicro, the time is formatted as an UNIX // timestamp as integer. TimeFieldFormat = time.RFC3339 // TimestampFunc defines the function called to generate a timestamp. TimestampFunc = time.Now // DurationFieldUnit defines the unit for time.Duration type fields added // using the Dur method. DurationFieldUnit = time.Millisecond // DurationFieldInteger renders Dur fields as integer instead of float if // set to true. DurationFieldInteger = false // ErrorHandler is called whenever zerolog fails to write an event on its // output. If not set, an error is printed on the stderr. This handler must // be thread safe and non-blocking. ErrorHandler func(err error) )
var File_log_proto protoreflect.FileDescriptor
var (
MultiLevelWriter = zlog.MultiLevelWriter
)
Functions ¶
func Debugf ¶
func Debugf(format string, v ...interface{})
Debugf calls the default logger's Debugf method.
func Errorf ¶
func Errorf(format string, v ...interface{})
Errorf calls the default logger's Errorf method.
func Fatalf ¶
func Fatalf(format string, v ...interface{})
Fatalf calls the default logger's Fatalf method and then os.Exit(1).
func Infof ¶
func Infof(format string, v ...interface{})
Infof calls the default logger's Infof method.
func Warnf ¶
func Warnf(format string, v ...interface{})
Warnf calls the default logger's Warnf method.
func WithLogger ¶ added in v1.0.5
func WithLogger(ctx context.Context, logger FullLogger) context.Context
WithLogger creates a new context with the provided logger attached.
Types ¶
type Config ¶
type Config struct { // level is the minimum severity level at which to log. e.g. "info". Level string `protobuf:"bytes,1,opt,name=level,proto3" json:"level,omitempty"` // path to the log file. e.g. "/var/log/my_app.log" Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"` // max_size is the maximum size to store in the log file. unit is MB. MaxSize int32 `protobuf:"varint,3,opt,name=max_size,json=maxSize,proto3" json:"max_size,omitempty"` // max_age is the maximum age of the log file. unit is days. MaxAge int32 `protobuf:"varint,4,opt,name=max_age,json=maxAge,proto3" json:"max_age,omitempty"` // contains filtered or unexported fields }
func (*Config) Descriptor
deprecated
func (*Config) GetMaxSize ¶
func (*Config) ProtoMessage ¶
func (*Config) ProtoMessage()
func (*Config) ProtoReflect ¶
func (x *Config) ProtoReflect() protoreflect.Message
type FormatLogger ¶
type FormatLogger interface { Debugf(format string, v ...interface{}) Infof(format string, v ...interface{}) Printf(format string, v ...interface{}) // Printf is an alias for Infof. Warnf(format string, v ...interface{}) Errorf(format string, v ...interface{}) Fatalf(format string, v ...interface{}) }
FormatLogger is a logger interface that output logs with a format.
type FullLogger ¶
type FullLogger interface { KLogger LevelLogger FormatLogger Control Clone() FullLogger WithTimestamp() FullLogger WithCaller() FullLogger WithCallerWithSkipFrameCount(skipFrameCount int) FullLogger WithStack() FullLogger WithFields(fields ...interface{}) FullLogger }
FullLogger is the combination of Logger, FormatLogger, CtxLogger and Control.
func Clone ¶
func Clone() FullLogger
func FromContext ¶ added in v1.0.5
func FromContext(ctx context.Context) FullLogger
FromContext returns the logger stored in the context. If no such logger exists, a default logger is returned.
func Init ¶
func Init(c *Config) FullLogger
func New ¶
func New(c *Config) FullLogger
func WithCaller ¶
func WithCaller() FullLogger
func WithCallerWithSkipFrameCount ¶
func WithCallerWithSkipFrameCount(skipFrameCount int) FullLogger
func WithFields ¶
func WithFields(fields ...interface{}) FullLogger
func WithStack ¶
func WithStack() FullLogger
func WithTimestamp ¶
func WithTimestamp() FullLogger
type Helper ¶ added in v1.0.2
type Helper struct {
// contains filtered or unexported fields
}
func (*Helper) Clone ¶ added in v1.0.2
func (ll *Helper) Clone() FullLogger
func (*Helper) WithCaller ¶ added in v1.0.2
func (ll *Helper) WithCaller() FullLogger
func (*Helper) WithCallerWithSkipFrameCount ¶ added in v1.0.2
func (ll *Helper) WithCallerWithSkipFrameCount(skipFrameCount int) FullLogger
func (*Helper) WithFields ¶ added in v1.0.2
func (ll *Helper) WithFields(fields ...interface{}) FullLogger
func (*Helper) WithStack ¶ added in v1.0.2
func (ll *Helper) WithStack() FullLogger
func (*Helper) WithTimestamp ¶ added in v1.0.2
func (ll *Helper) WithTimestamp() FullLogger
type Level ¶
func ParseLevel ¶
ParseLevel takes a string level and returns the logger log level constant.
type LevelLogger ¶
type LevelLogger interface { Debug(v ...interface{}) Info(v ...interface{}) Print(v ...interface{}) // Print is an alias of Info(). Warn(v ...interface{}) Error(v ...interface{}) Fatal(v ...interface{}) }
LevelLogger is a logger interface that provides logging function with levels.