Use library articles (a) Zap library of high-performance log: golang development

Why zap to write the log

Was originally written for PHP, I have been using the error_log, the first to write Go project, really do not know how to write the log, and later on its own is not a specification written according to fiddle with the wording of PHP. Then went to a new company, found that using a zap. Later inquiries learned under zap, former colleagues reflect their many large companies are using zap write the log, star on GitHub up to 7K more than enough to explain its popularity.

1.zap Uber is an open source logging library;
2. Many big companies and small companies are using;
3. Compared with seelog, logrus such as libraries, high performance is its most prominent advantage;
I think more than a few the reason has indicated its breadth, stability, it is worth to try.

How to use zap

We say that the simple use case for
the Prime Minister of course is downloaded
go get -u go.uber.org/zap
first posted my side a common configuration zap

zap.Config{
        Level:       zap.NewAtomicLevelAt(zap.DebugLevel),
        Development: true,
        Encoding:    "json",
        EncoderConfig: zapcore.EncoderConfig{
            TimeKey:        "t",
            LevelKey:       "level",
            NameKey:        "log",
            CallerKey:      "caller",
            MessageKey:     "msg",
            StacktraceKey:  "trace",
            LineEnding:     zapcore.DefaultLineEnding,
            EncodeLevel:    zapcore.LowercaseLevelEncoder,
            EncodeTime:     时间格式函数,
            EncodeDuration: zapcore.SecondsDurationEncoder,
            EncodeCaller:   zapcore.ShortCallerEncoder,
        },
        OutputPaths:      []string{"/tmp/zap.log"},
        ErrorOutputPaths: []string{"/tmp/zap.log"},
        InitialFields: map[string]interface{}{
            "app": "test",
        },
    }

Description of the basic configuration

Level: log level, with other languages ​​is the same. Type but it needs is AtomicLevel. To do so requires the use of zap.NewAtomicLevelAt under the following conversion.

zap.NewAtomicLevelAt(zap.DebugLevel)
zap.DebugLevel
zap.InfoLevel
zap.WarnLevel
zap.ErrorLevel

Development: bool whether the development environment. If a development model for DPanicLevel stack trace
DisableCaller: bool prohibit the use of the file name and line number of the calling function to annotate the log. The default is annotated log
DisableStacktrace: bool whether to disable the stack trace capture. Default Warn level and above the production level above error stack trace.
Encoding: encoding type, and two current json console according to [] separated by a space, commonly json
EncoderConfig: generating --TODO arranged behind some formats we look EncoderConfig detailed description of each configuration
OutputPaths: [] written to the log file address string
ErrorOutputPaths: [] string to the error record into the file system address
InitialFields: map [string] interface { } was added some initial field data, such as item name
, of course, if you want console output, OutputPaths not be configured as a file and ErrorOutputPaths address, and should be replaced stdout.

Configuration About config, the specific references which may comment
go.uber.org/zap/config.go
of the type struct Config

EncoderConfig configuration instructions

MessageKey: key name input information
LevelKey: Log output level key name
TimeKey: key name of the output time
NameKey CallerKey StacktraceKey similar with the above, see the name to know
LineEnding: each row delimiter. That is the basic zapcore.DefaultLineEnding "\ the n-"
EncodeLevel: Basic zapcore.LowercaseLevelEncoder. The log level string into lowercase
EncodeTime: time format output
EncodeDuration: general zapcore.SecondsDurationEncoder, execution consumed time into the second float
EncodeCaller: General zapcore.ShortCallerEncoder, in packets / file: line number formatting call stack
EncodeName: optional value.

EncoderConfig specific instructions, refer to the files inside the comment
go.uber.org/zapcore/encoder.go
of the type struct EncoderConfig

For chestnuts

You pull so many configuration instructions, and who has time to read this stuff, write a common enough so that everyone with a shining thing.

package main

import (
    "fmt"
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
    "time"
)

var logger *zap.Logger
func formatEncodeTime(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
    enc.AppendString(fmt.Sprintf("%d%02d%02d_%02d%02d%02d", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()))
}

func FormateLog(args []interface{}) *zap.Logger {
    log := logger.With(ToJsonData(args))
    return log
}

func Debug(msg string, args ...interface{}) {
    FormateLog(args).Sugar().Debugf(msg)
}

func ToJsonData(args []interface{}) zap.Field {
    det := make([]string, 0)
    if len(args) > 0 {
        for _, v := range args {
            det = append(det, fmt.Sprintf("%+v", v))
        }
    }
    zap := zap.Any("detail", det)
    return zap
}

func InitZapLog() {
    cfg := zap.Config{
        Level:       zap.NewAtomicLevelAt(zap.DebugLevel),
        Development: true,
        Encoding:    "json",
        EncoderConfig: zapcore.EncoderConfig{
            TimeKey:        "t",
            LevelKey:       "level",
            NameKey:        "logger",
            CallerKey:      "caller",
            MessageKey:     "msg",
            StacktraceKey:  "trace",
            LineEnding:     zapcore.DefaultLineEnding,
            EncodeLevel:    zapcore.LowercaseLevelEncoder,
            EncodeTime:     formatEncodeTime,
            EncodeDuration: zapcore.SecondsDurationEncoder,
            EncodeCaller:   zapcore.ShortCallerEncoder,
        },
        OutputPaths:      []string{"/tmp/zap.log"},
        ErrorOutputPaths: []string{"/tmp/zap.log"},
        InitialFields: map[string]interface{}{
            "app": "test",
        },
    }
    var err error
    logger, err = cfg.Build()
    if err != nil {
        panic("log init fail:" + err.Error())
    }
}

func main() {
    InitZapLog()
    defer logger.Sync()
    a := []string{"test","hello","world"}
    Debug("output",a)
}

Under the implementation, we will be entered in the log format configured on the log file.

tail -f /tmp/zap.log
{"level":"debug","t":"20190630_044053","caller":"myproject/main.go:21","msg":"output","app":"test","detail":["[test hello world]"]}

We then try console output, three modified configuration code associated console
?????
OutputPaths: [] {String "stdout"},
ErrorOutputPaths: [] {String "stdout"},
the console window is output
{ "level ":" debug "," t ":" 20190630_092533 "," caller ":" myproject / main.go: 21 "," msg ":" output "," app ":" test "," detail ": [" [Test Hello World] "]}
?????

Of course, zap most want to use and documentation, Tell me what network Well
https://github.com/uber-go/zap
https://godoc.org/go.uber.org/zap

Guess you like

Origin www.cnblogs.com/feixiangmanon/p/11108699.html