目录
- Log包
- 基本用法
- flag属性
- prefix属性
- out属性
- 创建新的Logger
- 自定义Go Logger
- 设置
- 使用
- 运行
- Zap
- 安装
- 配置Zap Logger
- Logger
- Sugared Logger
- 定制logger
- Lumberjack 日志切割
- 安装
- 使用
- Zap接收Gin默认日志
- 基于zap的中间件
- 在gin项目中使用zap
Log包
Go语言提供的默认日志包:https://golang.org/pkg/log/
基本用法
log包定义了Logger类型,该类型提供了一些格式化输出的方法。
type Logger struct { mu sync.Mutex // ensures atomic writes; protects the following fields prefix string // prefix on each line to identify the logger (but see Lmsgprefix) flag int // properties out io.Writer // destination for output buf []byte // for accumulating text to write }
muprefixflagout
(Print|Printf|Println)(Fatal|Fatalf|Fatalln)(Panic|Panicf|Panicln)
例如,我们可以像下面的代码一样直接通过log包来调用上面提到的方法,默认它们会将日志信息打印到终端界面:
log.Println("这是一条优雅的日志。") v := "优雅的" log.Printf("这是一个%s日志 ", v) //fatal系列函数会在写入日志信息后调用os.Exit(1) log.Fatalln("这是一天会触发fatal的日志") //Panic系列函数会在写入日志信息后panic log.Panicln("这是一个会触发panic的日志。") //执行后会自动触发一个异常
flag属性
默认情况下的logger只会提供日志的时间信息,但是很多情况下我们希望得到更多信息,比如记录该日志的文件名和行号等。log标准库中为我们提供了定制这些设置的方法。
FlagsSetFlags
const ( Ldate = 1 << iota // the date in the local time zone: 2009/01/23 Ltime // the time in the local time zone: 01:23:23 Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime. Llongfile // full file name and line number: /a/b/c/d.go:23 Lshortfile // final file name element and line number: d.go:23. overrides Llongfile LUTC // if Ldate or Ltime is set, use UTC rather than the local time zone Lmsgprefix // move the "prefix" from the beginning of the line to before the message LstdFlags = Ldate | Ltime // initial values for the standard logger )
设置输出属性的代码如下:
func main() { log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate) log.Println("这是一条优雅的日志。") }
编译输出:
2020/07/14 22:51:06.079594 D:/xxx/test_log.go:24: 这是一条优雅的日志。
prefix属性
log标准库中还提供了关于日志信息前缀的两个方法:其中Prefix函数用来查看标准logger的输出前缀,SetPrefix函数用来设置输出前缀。
func Prefix() string func SetPrefix(prefix string)
设置日志输出前缀的代码如下:
func main() { log.SetPrefix("[PS]") log.Println("这是一条很普通的日志。") }
编译输出:
[PS]2020/07/14 22:56:15.652555 D:/xxx/test_log.go:26: 这是一个普通的日志
out属性
out属性是一个io.Writer输出流,使用它可以把日志输出为文件。
需要用的方法为:设置标准logger的输出目的地,默认是标准错误输出。
func SetOutput(w io.Writer)
例如,下面的代码会把日志输出到同目录下的xx.log文件中。
func main() { logFile, err := os.OpenFile("./xx.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) if err != nil { fmt.Println("open log file failed, err:", err) return } log.SetOutput(logFile) log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate) log.Println("这是一条很普通的日志。") log.SetPrefix("[PS]") log.Println("这是一条很普通的日志。") }
如果你要使用标准的logger,我们通常会把上面的配置操作写到init函数中。
func init() { logFile, err := os.OpenFile("./xx.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) if err != nil { fmt.Println("open log file failed, err:", err) return } log.SetOutput(logFile) log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate) }
创建新的Logger
log标准库中还提供了一个创建新logger对象的构造函数 New,支持我们创建自己的logger示例。New函数的签名如下:
func New(out io.Writer, prefix string, flag int) *Logger
New创建一个Logger对象。其中,参数out设置日志信息写入的目的地。参数prefix会添加到生成的每一条日志前面。参数flag定义日志的属性(时间、文件等等)。
举个例子:
func main() { logger := log.New(os.Stdout, "<PS>", log.Lshortfile|log.Ldate|log.Ltime) logger.Println("这是自定义的logger记录的日志。") }
编译输出:
<PS>2020/07/14 23:02:59 test_log.go:43: 这是自定义的logger记录的日志
自定义Go Logger
io.Writer
设置
func SetupLogger() { logFileLocation, _ := os.OpenFile("./test.log", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0744) log.SetOutput(logFileLocation) }
使用
func test(){ log.Printf("Test log: %s %s", "Hello", "World") }
运行
func main() { SetupLogger() test() }
Zap
Zap是非常快的、结构化的,分日志级别的Go日志库。
安装
go get -u go.uber.org/zap
配置Zap Logger
Sugared LoggerLogger
- Logger更快,但只支持强类型的结构化日志记录。
- Sugared Logger支持结构化和printf风格的日志记录。
Logger
zap.NewProduction()zap.NewDevelopment()zap.Example()ExampleProductionjsonDevelopmentDevelopmentProduction
var logger *zap.Logger func main() { InitLogger() defer logger.Sync() simpleHttpGet("www.google.com") simpleHttpGet("http://www.google.com") } func InitLogger() { logger, _ = zap.NewProduction() } func simpleHttpGet(url string) { resp, err := http.Get(url) if err != nil { logger.Error( "Error fetching url..", zap.String("url", url), zap.Error(err)) } else { logger.Info("Success..", zap.String("statusCode", resp.Status), zap.String("url", url)) resp.Body.Close() } }
在上面的代码中,我们首先创建了一个Logger,然后使用Info/ Error等Logger方法记录消息。
日志记录器方法的语法是这样的:
func (log *Logger) MethodXXX(msg string, fields ...Field)
MethodXXXzapcore.Field
zapcore.Field
我们执行上面的代码会得到如下输出结果:
{"level":"error","ts":1572159218.912792,"caller":"zap_demo/temp.go:25","msg":"Error fetching url..","url":"www.sogo.com","error":"Get www.sogo.com: unsupported protocol scheme ""","stacktrace":"main.simpleHttpGet /Users/itxiaoma/zap_demo/temp.go:25 main.main /Users/itxiaoma/zap_demo/temp.go:14 runtime.main /usr/local/go/src/runtime/proc.go:203"}
{"level":"info","ts":1572159219.1227388,"caller":"zap_demo/temp.go:30","msg":"Success..","statusCode":"200 OK","url":"http://www.sogo.com"}
Sugared Logger
slogger := logger.Sugar()
suger loggerprintf
var sugarLogger *zap.SugaredLogger func main() { InitLogger() defer sugarLogger.Sync() simpleHttpGet("www.google.com") simpleHttpGet("http://www.google.com") } func InitLogger() { logger, _ := zap.NewProduction() sugarLogger = logger.Sugar() } func simpleHttpGet(url string) { sugarLogger.Debugf("Trying to hit GET request for %s", url) resp, err := http.Get(url) if err != nil { sugarLogger.Errorf("Error fetching URL %s : Error = %s", url, err) } else { sugarLogger.Infof("Success! statusCode = %s for URL %s", resp.Status, url) resp.Body.Close() } }
执行结果:
{"level":"error","ts":1572159149.923002,"caller":"logic/temp2.go:27","msg":"Error fetching URL www.sogo.com : Error = Get www.sogo.com: unsupported protocol scheme ""","stacktrace":"main.simpleHttpGet /Users/itxiaoma/zap_demo/logic/temp2.go:27 main.main /Users/itxiaoma/zap_demo/logic/temp2.go:14 runtime.main /usr/local/go/src/runtime/proc.go:203"}
{"level":"info","ts":1572159150.192585,"caller":"logic/temp2.go:29","msg":"Success! statusCode = 200 OK for URL http://www.sogo.com"}
定制logger
1. 日志写入文件
zap.New(…)zap.NewProduction()
func New(core zapcore.Core, options ...Option) *Logger
NewJSONEncoder()ProductionEncoderConfig()
zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
zapcore.AddSync()
file, _ := os.Create("./test.log") writeSyncer := zapcore.AddSync(file)
Log Level:哪种级别的日志将被写入。
func InitLogger() { writeSyncer := getLogWriter() encoder := getEncoder() core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel) logger := zap.New(core) sugarLogger = logger.Sugar() } func getEncoder() zapcore.Encoder { return zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()) } func getLogWriter() zapcore.WriteSyncer { file, _ := os.Create("./test.log") return zapcore.AddSync(file) }
main()test.log
{"level":"debug","ts":1572160754.994731,"msg":"Trying to hit GET request for www.sogo.com"}
{"level":"error","ts":1572160754.994982,"msg":"Error fetching URL www.sogo.com : Error = Get www.sogo.com: unsupported protocol scheme """}
{"level":"debug","ts":1572160754.994996,"msg":"Trying to hit GET request for http://www.sogo.com"}
{"level":"info","ts":1572160757.3755069,"msg":"Success! statusCode = 200 OK for URL http://www.sogo.com"}
2.将JSON Encoder更改为普通的Log Encoder
NewJSONEncoder()NewConsoleEncoder()
return zapcore.NewConsoleEncoder(zap.NewProductionEncoderConfig())
main()test.log
1.572161051846623e+09 debug Trying to hit GET request for www.sogo.com
1.572161051846828e+09 error Error fetching URL www.sogo.com : Error = Get www.sogo.com: unsupported protocol scheme ""
1.5721610518468401e+09 debug Trying to hit GET request for http://www.sogo.com
1.572161052068744e+09 info Success! statusCode = 200 OK for URL http://www.sogo.com
3. 更改时间编码并添加调用者详细信息
修改时间编码器:
func getEncoder() zapcore.Encoder { encoderConfig := zap.NewProductionEncoderConfig() encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder return zapcore.NewConsoleEncoder(encoderConfig) }
zap.New(..)Option
logger := zap.New(core, zap.AddCaller())
最终结果:
2019-10-27T15:33:29.855+0800 DEBUG logic/temp2.go:47 Trying to hit GET request for www.sogo.com
2019-10-27T15:33:29.855+0800 ERROR logic/temp2.go:50 Error fetching URL www.sogo.com : Error = Get www.sogo.com: unsupported protocol scheme ""
2019-10-27T15:33:29.856+0800 DEBUG logic/temp2.go:47 Trying to hit GET request for http://www.sogo.com
2019-10-27T15:33:30.125+0800 INFO logic/temp2.go:52 Success! statusCode = 200 OK for URL http://www.sogo.com
Lumberjack 日志切割
安装
go get -u github.com/natefinch/lumberjack
使用
func getLogWriter() zapcore.WriteSyncer { lumberJackLogger := &lumberjack.Logger{ Filename: "./test.log", MaxSize: 10, MaxBackups: 5, MaxAge: 30, Compress: false, } return zapcore.AddSync(lumberJackLogger) }
Lumberjack Logger采用以下属性作为输入:
- Filename: 日志文件的位置
- MaxSize:在进行切割之前,日志文件的最大大小(以MB为单位)
- MaxBackups:保留旧文件的最大个数
- MaxAges:保留旧文件的最大天数
- Compress:是否压缩/归档旧文件
Zap接收Gin默认日志
gin.Default()Logger()Recovery()
Logger()Recovery()
基于zap的中间件
gin.Default()
r := gin.New() r.Use(GinLogger(), GinRecovery())
中间件:
// GinLogger 接收gin框架默认的日志 func GinLogger(logger *zap.Logger) gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() path := c.Request.URL.Path query := c.Request.URL.RawQuery c.Next() cost := time.Since(start) logger.Info(path, zap.Int("status", c.Writer.Status()), zap.String("method", c.Request.Method), zap.String("path", path), zap.String("query", query), zap.String("ip", c.ClientIP()), zap.String("user-agent", c.Request.UserAgent()), zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()), zap.Duration("cost", cost), ) } } // GinRecovery recover掉项目可能出现的panic func GinRecovery(logger *zap.Logger, stack bool) gin.HandlerFunc { return func(c *gin.Context) { defer func() { if err := recover(); err != nil { // Check for a broken connection, as it is not really a // condition that warrants a panic stack trace. var brokenPipe bool if ne, ok := err.(*net.OpError); ok { if se, ok := ne.Err.(*os.SyscallError); ok { if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") { brokenPipe = true } } } httpRequest, _ := httputil.DumpRequest(c.Request, false) if brokenPipe { logger.Error(c.Request.URL.Path, zap.Any("error", err), zap.String("request", string(httpRequest)), ) // If the connection is dead, we can"t write a status to it. c.Error(err.(error)) // nolint: errcheck c.Abort() return } if stack { logger.Error("[Recovery from panic]", zap.Any("error", err), zap.String("request", string(httpRequest)), zap.String("stack", string(debug.Stack())), ) } else { logger.Error("[Recovery from panic]", zap.Any("error", err), zap.String("request", string(httpRequest)), ) } c.AbortWithStatus(http.StatusInternalServerError) } }() c.Next() } }
如果不想自己实现,可以使用github上有别人封装好的https://github.com/gin-contrib/zap。
Logger()Recovery()
在gin项目中使用zap
logger.go
package logger import ( "gin_zap_demo/config" "net" "net/http" "net/http/httputil" "os" "runtime/debug" "strings" "time" "github.com/gin-gonic/gin" "github.com/natefinch/lumberjack" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) var lg *zap.Logger // InitLogger 初始化Logger func InitLogger(cfg *config.LogConfig) (err error) { writeSyncer := getLogWriter(cfg.Filename, cfg.MaxSize, cfg.MaxBackups, cfg.MaxAge) encoder := getEncoder() var l = new(zapcore.Level) err = l.UnmarshalText([]byte(cfg.Level)) if err != nil { return } core := zapcore.NewCore(encoder, writeSyncer, l) lg = zap.New(core, zap.AddCaller()) zap.ReplaceGlobals(lg) // 替换zap包中全局的logger实例,后续在其他包中只需使用zap.L()调用即可 return } func getEncoder() zapcore.Encoder { encoderConfig := zap.NewProductionEncoderConfig() encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder encoderConfig.TimeKey = "time" encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder encoderConfig.EncodeDuration = zapcore.SecondsDurationEncoder encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder return zapcore.NewJSONEncoder(encoderConfig) } func getLogWriter(filename string, maxSize, maxBackup, maxAge int) zapcore.WriteSyncer { lumberJackLogger := &lumberjack.Logger{ Filename: filename, MaxSize: maxSize, MaxBackups: maxBackup, MaxAge: maxAge, } return zapcore.AddSync(lumberJackLogger) } // GinLogger 接收gin框架默认的日志 func GinLogger() gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() path := c.Request.URL.Path query := c.Request.URL.RawQuery c.Next() cost := time.Since(start) lg.Info(path, zap.Int("status", c.Writer.Status()), zap.String("method", c.Request.Method), zap.String("path", path), zap.String("query", query), zap.String("ip", c.ClientIP()), zap.String("user-agent", c.Request.UserAgent()), zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()), zap.Duration("cost", cost), ) } } // GinRecovery recover掉项目可能出现的panic,并使用zap记录相关日志 func GinRecovery(stack bool) gin.HandlerFunc { return func(c *gin.Context) { defer func() { if err := recover(); err != nil { // Check for a broken connection, as it is not really a // condition that warrants a panic stack trace. var brokenPipe bool if ne, ok := err.(*net.OpError); ok { if se, ok := ne.Err.(*os.SyscallError); ok { if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") { brokenPipe = true } } } httpRequest, _ := httputil.DumpRequest(c.Request, false) if brokenPipe { lg.Error(c.Request.URL.Path, zap.Any("error", err), zap.String("request", string(httpRequest)), ) // If the connection is dead, we can"t write a status to it. c.Error(err.(error)) // nolint: errcheck c.Abort() return } if stack { lg.Error("[Recovery from panic]", zap.Any("error", err), zap.String("request", string(httpRequest)), zap.String("stack", string(debug.Stack())), ) } else { lg.Error("[Recovery from panic]", zap.Any("error", err), zap.String("request", string(httpRequest)), ) } c.AbortWithStatus(http.StatusInternalServerError) } }() c.Next() } }
然后定义日志相关配置:
type LogConfig struct { Level string `json:"level"` Filename string `json:"filename"` MaxSize int `json:"maxsize"` MaxAge int `json:"max_age"` MaxBackups int `json:"max_backups"` }
logger.InitLogger(config.Conf.LogConfig)r.Use(logger.GinLogger(), logger.GinRecovery(true))zap.L().Xxx()
package main import ( "fmt" "gin_zap_demo/config" "gin_zap_demo/logger" "net/http" "os" "go.uber.org/zap" "github.com/gin-gonic/gin" ) func main() { // load config from config.json if len(os.Args) < 1 { return } if err := config.Init(os.Args[1]); err != nil { panic(err) } // init logger if err := logger.InitLogger(config.Conf.LogConfig); err != nil { fmt.Printf("init logger failed, err:%v ", err) return } gin.SetMode(config.Conf.Mode) r := gin.Default() // 注册zap相关中间件 r.Use(logger.GinLogger(), logger.GinRecovery(true)) r.GET("/hello", func(c *gin.Context) { // 假设你有一些数据需要记录到日志中 var ( name = "itxiaoma" age = 18 ) // 记录日志并使用zap.Xxx(key, val)记录相关字段 zap.L().Debug("this is hello func", zap.String("user", name), zap.Int("age", age)) c.String(http.StatusOK, "hello itxiaoma!") }) addr := fmt.Sprintf(":%v", config.Conf.Port) r.Run(addr) }