Golang学习笔记-zerolog

zerolog是一个高性能,支持日志等级,钩子的结构化日志库。log的Print()和Printf()方法默认输出到os.Stderr,默认日志等级为debug,用法和官方log库相同。

package main

import (
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)


func main(){
	zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
	log.Print("hello world")
}
{"level":"debug","time":1576398679,"message":"hello world"}

日志等级

zerolog有下面几种日志等级,调用zerolog.SetGlobalLevel()设置日志等级。

  • panic (zerolog.PanicLevel, 5)
  • fatal (zerolog.FatalLevel, 4)
  • error (zerolog.ErrorLevel, 3)
  • warn (zerolog.WarnLevel, 2)
  • info (zerolog.InfoLevel, 1)
  • debug (zerolog.DebugLevel, 0)
  • trace (zerolog.TraceLevel, -1)

添加数据到上下文

zerolog可以将数据以key-value对的形式添加到一条日志事件的上下文中,重复的key-value对不会删除。调用Msg方法输出日志,也可以调用Send方法输出日志,其本质是调用Msg("")。

package main

import (
	"github.com/rs/zerolog/log"
)


func main(){
	log.Debug().
		Str("name", "xy").
		Str("name", "xy").
		Float64("height", 100.0).
		Msg("create object")
}

{"level":"debug","name":"xy","name":"xy","height":100,"time":"2019-12-15T17:17:46+08:00","message":"create object"}

自定义字段名

package main

import (
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)


func main(){
	zerolog.TimestampFieldName = "t"
	zerolog.LevelFieldName = "l"
	zerolog.MessageFieldName = "m"
	log.Debug().
		Str("name", "xy").
		Float64("height", 100.0).
		Msg("create object")
}
{"l":"debug","name":"xy","height":100,"t":"2019-12-15T17:04:24+08:00","m":"create object"}

添加文件名和代码行

package main

import (
	"github.com/rs/zerolog/log"
)


func main(){
	log.Logger = log.With().Caller().Logger()
	log.Info().Msg("hello world")
}

{"level":"info","time":"2019-12-15T17:13:02+08:00","caller":"C:/Users/Administrator/go/src/studygo/main.go:10","message":"hello world"}

logger

zerolog可以创建不同的logger实例来输出日志,下面代码创建了一个新的logger替换了log的logger,其中zerolog.ConsoleWriter可以使输出的日志更加友好,日志等级变为彩色的。

package main

import (
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"os"
)


func main(){
	log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr,TimeFormat: "2006-01-02 15:04:05.000"})
	log.Info().Msg("hello world")
}

钩子

利用钩子可以拦截日志事件,从而实现各种扩展功能,例如将日志输出到文件。

package main

import (
	"fmt"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

type LogHook struct{}

func (hook LogHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
	fmt.Println(msg)
}

func main(){
	log.Logger=log.Hook(LogHook{})
	log.Info().Msg("hello world")
}

hello world
{"level":"info","time":"2019-12-15T17:28:58+08:00","message":"hello world"}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页