log

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2022 License: MIT Imports: 12 Imported by: 0

README

go-project-pkg/log

Wrap zap for easy using.

Installation

$ go get -u github.com/go-project-pkg/log

Usage

Use default logger:

import "github.com/go-project-pkg/log"

func main() {
    defer log.Sync()

    log.Info("Hello world!")
    log.Info("Hello ", log.String("string_key", "value"), log.Int("int_key", 666))
    log.Infof("Hello %s!", "world")
    log.Infow("Hello ", "string_key", "value", "int_key", 666)

    log.WithName("logger1").Warn("I am logger1")
    log.WithName("logger2").Warn("I am logger2")

    log.WithFields(log.String("f1", "value"), log.Int("f2", 888)).Error("Hello world!")
    log.WithName("logger3").WithFields(log.String("f1", "value"), log.Int("f2", 888)).Error("Hello world!")

    ctx := log.WithFields(String("f1", "value"), Int("f2", 888)).ToContext(context.Background())
    log.FromContext(ctx).Info("hello world!")
}

Custom your own logger:

import "github.com/go-project-pkg/log"

func init() {
    opts := &log.Options{
        Name:              "",        // logger name
        Level:             "debug",   // debug, info, warn, error, panic, dpanic, fatal
        Format:            "console", // json, console/text
        DisableColor:      false,
        DisableCaller:     false,
        DisableStacktrace: false,
        // Aplication's all levels logs.
        OutputPaths: []string{
            "stdout", // os.Stdout
            "/var/log/app/app.log",
        },
        // Only include zap internal errors, not include application's any level logs.
        ErrorOutputPaths: []string{
            "stderr", // os.Stderr
            "/var/log/app/error.log",
        },
        // Enable log files rotation feature or not.
        EnableRotate: true,
        // Take effect when EnableRotate is true.
        RotateOptions: &log.RotateOptions{
            // Maximum size in megabytes of the log file before it gets rotated.
            // Default: 100, if the value is 0, the log files will not be rotated.
            MaxSize:    1,
            // Saved days, default 0, means no limit.
            MaxAge:     30,
            // Saved count, default 0, means no limit.
            MaxBackups: 2,
            // Use local time in log file name, default false.
            LocalTime:  true,
            // Gzip log files, default false.
            Compress:   false,
        },
    }

    log.Init(opts)
}

func main() {
    defer log.Sync()

    log.Info("Hello world!")
    log.Info("Hello ", log.String("string_key", "value"), log.Int("int_key", 666))
    log.Infof("Hello %s!", "world")
    log.Infow("Hello ", "string_key", "value", "int_key", 666)

    log.WithName("logger1").Warn("I am logger1")
    log.WithName("logger2").Warn("I am logger2")

    log.WithFields(log.String("f1", "value"), log.Int("f2", 888)).Error("Hello world!")
    log.WithName("logger3").WithFields(log.String("f1", "value"), log.Int("f2", 888)).Error("Hello world!")

    ctx := log.WithFields(String("f1", "value"), Int("f2", 888)).ToContext(context.Background())
    log.FromContext(ctx).Info("hello world!")

    // log files rotation test
    for i := 0; i <= 20000; i++ {
        log.Infof("hello world: %d", i)
    }
}

Use log.C(ctx context.Context) for getting logger with additional log fields by cooperating with gin's middleware:

import "github.com/go-project-pkg/log"

// A middleware of gin for setting logger that with custom fileds to gin.Context
func Context() gin.HandlerFunc {
    return func(c *gin.Context) {
        l := log.WithFields(
            log.String("x-request-id", c.GetString(XRequestIDKey)),
            log.String("username", c.GetString(UsernameKey)),
        )
        c.Set(log.ContextLoggerName, l)

        c.Next()
    }
}

// Others place that use the logger.
func (u *UserController) Get(c *gin.Context) {
    // Get logger that with fileds from gin.Context and log a message.
    log.C(c).Debug("user get called")
}

You can add hooks to realize some useful features, like alerting when encountering error logs.

Use log.SetHooks(hooks ...log.Hook) for global logger:

func main() {
    defer log.Sync()

    monitorHook1 := func(entry log.Entry) error {
        if entry.Level >= log.ErrorLevel {
            fmt.Printf("hook1 alert! log entry: %v", entry)
        }

        // This error is zap internal error, and it will write to 'ErrorOutputPaths'.
        return errors.New("alert hook failed")
    }

    monitorHook2 := func(entry log.Entry) error {
        if entry.Level >= log.ErrorLevel {
            fmt.Println("hook2 alert! log entry: %v", entry)
        }

        return nil
    }

    log.SetHooks(monitorHook1, monitorHook2)

    log.Error("set hooks: server error")
}

Use log.WithHooks(hooks ...log.Hook) for current logger instance:

func main() {
    defer log.Sync()

    monitorHook1 := func(entry log.Entry) error {
        if entry.Level >= log.ErrorLevel {
            fmt.Println("hook1 alert! log entry: %v", entry)
        }

        // This error is zap internal error, and it will write to 'ErrorOutputPaths'.
        return errors.New("alert hook failed")
    }

    log.WithHooks(monitorHook1).Error("with hooks: server error")
}

License

This project is under the MIT License. See the LICENSE file for the full license text.

Documentation

Index

Constants

View Source
const (
	// ContextLoggerName is logger key from context.Context.
	ContextLoggerName = "contextLgger"
)

Variables

View Source
var (
	DebugLevel  = zapcore.DebugLevel
	InfoLevel   = zapcore.InfoLevel
	WarnLevel   = zapcore.WarnLevel
	ErrorLevel  = zapcore.ErrorLevel
	DPanicLevel = zapcore.DPanicLevel
	PanicLevel  = zapcore.PanicLevel
	FatalLevel  = zapcore.FatalLevel
)

Alias for zap level.

View Source
var (
	Any         = zap.Any
	Array       = zap.Array
	Object      = zap.Object
	Binary      = zap.Binary
	Bool        = zap.Bool
	Bools       = zap.Bools
	ByteString  = zap.ByteString
	ByteStrings = zap.ByteStrings
	Complex64   = zap.Complex64
	Complex64s  = zap.Complex64s
	Complex128  = zap.Complex128
	Complex128s = zap.Complex128s
	Duration    = zap.Duration
	Durations   = zap.Durations
	Err         = zap.Error
	Errors      = zap.Errors
	Float32     = zap.Float32
	Float32s    = zap.Float32s
	Float64     = zap.Float64
	Float64s    = zap.Float64s
	Int         = zap.Int
	Ints        = zap.Ints
	Int8        = zap.Int8
	Int8s       = zap.Int8s
	Int16       = zap.Int16
	Int16s      = zap.Int16s
	Int32       = zap.Int32
	Int32s      = zap.Int32s
	Int64       = zap.Int64
	Int64s      = zap.Int64s
	Namespace   = zap.Namespace
	Reflect     = zap.Reflect
	Stack       = zap.Stack
	String      = zap.String
	Stringer    = zap.Stringer
	Strings     = zap.Strings
	Time        = zap.Time
	Times       = zap.Times
	Uint        = zap.Uint
	Uints       = zap.Uints
	Uint8       = zap.Uint8
	Uint8s      = zap.Uint8s
	Uint16      = zap.Uint16
	Uint16s     = zap.Uint16s
	Uint32      = zap.Uint32
	Uint32s     = zap.Uint32s
	Uint64      = zap.Uint64
	Uint64s     = zap.Uint64s
	Uintptr     = zap.Uintptr
	Uintptrs    = zap.Uintptrs
)

Alias for zap type functions.

View Source
var (
	Debug  = std.Debug
	Debugf = std.Debugf
	Debugw = std.Debugw

	Info  = std.Info
	Infof = std.Infof
	Infow = std.Infow

	Warn  = std.Warn
	Warnf = std.Warnf
	Warnw = std.Warnw

	Error  = std.Error
	Errorf = std.Errorf
	Errorw = std.Errorw

	DPanic  = std.DPanic
	DPanicf = std.DPanicf
	DPanicw = std.DPanicw

	Panic  = std.Panic
	Panicf = std.Panicf
	Panicw = std.Panicw

	Fatal  = std.Fatal
	Fatalf = std.Fatalf
	Fatalw = std.Fatalw

	Sync = std.Sync

	WithName   = std.WithName
	WithFields = std.WithFields
	WithHooks  = std.WithHooks

	ToContext   = std.ToContext
	FromContext = std.FromContext

	GetOptions = std.GetOptions

	C = std.C
)

User can directly use package level functions

Functions

func Init

func Init(opts *Options)

Init package default logger instance with given options.

func SetHooks added in v0.1.2

func SetHooks(hooks ...Hook)

SetHooks and replace global logger.

Usage e.g.:

monitorHook := func(entry log.Entry) error {
	  if entry.Level >= log.ErrorLevel {
       fmt.Println("alert!")
   }
   return nil
}

log.SetHooks(monitorHook)

log.Error("server failed")

Types

type Entry added in v0.1.2

type Entry = zapcore.Entry

Entry ...

type Field

type Field = zapcore.Field

Field ...

type Hook added in v0.1.2

type Hook = func(entry Entry) error

Hook ...

type Level

type Level = zapcore.Level

Level ...

type Logger

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

Logger ...

func New

func New(opts *Options) *Logger

New logger instance with given options.

func (*Logger) C added in v0.1.1

func (l *Logger) C(ctx context.Context) *Logger

C get logger from gin.Context.

Usage example:

This is a middleware that put logger into gin.Context:

func Context() gin.HandlerFunc { return func(c *gin.Context) { l := log.WithFields( log.String("x-request-id", c.GetString(XRequestIDKey)), log.String("username", c.GetString(UsernameKey)), ) c.Set(log.ContextLoggerName, l) c.Next() } }

Get logger that with fileds from gin.Context:

func (u *UserController) Get(c *gin.Context) { log.C(c).Debug("user get called") }

func (*Logger) DPanic

func (l *Logger) DPanic(msg string, fields ...Field)

DPanic ...

func (*Logger) DPanicf

func (l *Logger) DPanicf(format string, v ...interface{})

DPanicf ...

func (*Logger) DPanicw

func (l *Logger) DPanicw(msg string, keysAndValues ...interface{})

DPanicw ...

func (*Logger) Debug

func (l *Logger) Debug(msg string, fields ...Field)

Debug ...

func (*Logger) Debugf

func (l *Logger) Debugf(format string, v ...interface{})

Debugf ...

func (*Logger) Debugw

func (l *Logger) Debugw(msg string, keysAndValues ...interface{})

Debugw ...

func (*Logger) Error

func (l *Logger) Error(msg string, fields ...Field)

Error ...

func (*Logger) Errorf

func (l *Logger) Errorf(format string, v ...interface{})

Errorf ...

func (*Logger) Errorw

func (l *Logger) Errorw(msg string, keysAndValues ...interface{})

Errorw ...

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, fields ...Field)

Fatal ...

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, v ...interface{})

Fatalf ...

func (*Logger) Fatalw

func (l *Logger) Fatalw(msg string, keysAndValues ...interface{})

Fatalw ...

func (*Logger) FromContext added in v0.1.1

func (l *Logger) FromContext(ctx context.Context) *Logger

FromContext return logger from context.

func (*Logger) GetOptions added in v0.1.3

func (l *Logger) GetOptions() *Options

GetOptions get logger instance configuration.

func (*Logger) Info

func (l *Logger) Info(msg string, fields ...Field)

Info ...

func (*Logger) Infof

func (l *Logger) Infof(format string, v ...interface{})

Infof ...

func (*Logger) Infow

func (l *Logger) Infow(msg string, keysAndValues ...interface{})

Infow ...

func (*Logger) Panic

func (l *Logger) Panic(msg string, fields ...Field)

Panic ...

func (*Logger) Panicf

func (l *Logger) Panicf(format string, v ...interface{})

Panicf ...

func (*Logger) Panicw

func (l *Logger) Panicw(msg string, keysAndValues ...interface{})

Panicw ...

func (*Logger) Sync

func (l *Logger) Sync()

Sync memory data to log files.

func (*Logger) ToContext added in v0.1.1

func (l *Logger) ToContext(ctx context.Context) context.Context

ToContext put logger to context.

func (*Logger) Warn

func (l *Logger) Warn(msg string, fields ...Field)

Warn ...

func (*Logger) Warnf

func (l *Logger) Warnf(format string, v ...interface{})

Warnf ...

func (*Logger) Warnw

func (l *Logger) Warnw(msg string, keysAndValues ...interface{})

Warnw ...

func (*Logger) WithFields

func (l *Logger) WithFields(fields ...Field) *Logger

WithFields custom other log entry fileds.

func (*Logger) WithHooks added in v0.1.2

func (l *Logger) WithHooks(hooks ...Hook) *Logger

WithHooks is different from SetHooks, SetHooks is for global logger, WithHooks is for the new logger.

func (*Logger) WithName

func (l *Logger) WithName(name string) *Logger

WithName custom logger name.

type Options

type Options struct {
	*RotateOptions

	// logger name, default ""
	Name              string
	Level             string
	Format            string
	DisableColor      bool
	DisableCaller     bool
	DisableStacktrace bool
	OutputPaths       []string
	ErrorOutputPaths  []string
	EnableRotate      bool
}

Options for logger.

type RotateOptions

type RotateOptions struct {
	// MaxSize is the maximum size in megabytes of the log file before it gets
	// rotated. It defaults to 100 megabytes.
	MaxSize int

	// MaxAge is the maximum number of days to retain old log files based on the
	// timestamp encoded in their filename.  Note that a day is defined as 24
	// hours and may not exactly correspond to calendar days due to daylight
	// savings, leap seconds, etc. The default is not to remove old log files
	// based on age.
	MaxAge int

	// MaxBackups is the maximum number of old log files to retain.  The default
	// is to retain all old log files (though MaxAge may still cause them to get
	// deleted.)
	MaxBackups int

	// LocalTime determines if the time used for formatting the timestamps in
	// backup files is the computer's local time.  The default is to use UTC
	// time.
	LocalTime bool

	// Compress determines if the rotated log files should be compressed
	// using gzip. The default is not to perform compression.
	Compress bool
}

RotateOptions for log rotate feature.

Jump to

Keyboard shortcuts

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