golang 日志库
golangprintpanicfatal
logruslogrusdockerprometheus
zap 是 Uber 推出的一个快速、结构化的分级日志库.具有强大的 ad-hoc 分析功能,并且具有灵活的仪表盘.zap 目前在 GitHub 上的 star 数量约为 4.3k. seelog 提供了灵活的异步调度、格式化和过滤功能.目前在 GitHub 上也有约 1.1k.
logrus 特性
logrus.Debug("Useful debugging information.")logrus.Info("Something noteworthy happened!")logrus.Warn("You should probably take a look at this.")logrus.Error("Something failed but I'm not quitting.")logrus.Fatal("Bye.")logrus.Panic("I'm bailing.")logstashelasticsearchmqJSONFormatterTextFormatterFieldlogruslogrus*Entry,Entrytime:entry.Info()
logrus 的使用
1.基本用法
package main
import (
log "github.com/sirupsen/logrus"
)
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
}).Info("A walrus appears")
}
上面代码执行后,标准输出上输出如下:
time="2018-08-11T15:42:22+08:00" level=info msg="A walrus appears" animal=walrus
logruslog“github.com/sirupsen/logrus”logrus
package main
import (
"os"
log "github.com/sirupsen/logrus"
)
func init() {
// 设置日志格式为json格式
log.SetFormatter(&log.JSONFormatter{})
// 设置将日志输出到标准输出(默认的输出为stderr,标准错误)
// 日志消息输出可以是任意的io.writer类型
log.SetOutput(os.Stdout)
// 设置日志级别为warn以上
log.SetLevel(log.WarnLevel)
}
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
log.WithFields(log.Fields{
"omg": true,
"number": 122,
}).Warn("The group's number increased tremendously!")
log.WithFields(log.Fields{
"omg": true,
"number": 100,
}).Fatal("The ice breaks!")
}
2.自定义 Logger
logloggerlogruslogger
package main
import (
"github.com/sirupsen/logrus"
"os"
)
// logrus提供了New()函数来创建一个logrus的实例.
// 项目中,可以创建任意数量的logrus实例.
var log = logrus.New()
func main() {
// 为当前logrus实例设置消息的输出,同样地,
// 可以设置logrus实例的输出到任意io.writer
log.Out = os.Stdout
// 为当前logrus实例设置消息输出格式为json格式.
// 同样地,也可以单独为某个logrus实例设置日志级别和hook,这里不详细叙述.
log.Formatter = &logrus.JSONFormatter{}
log.WithFields(logrus.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
}
3.Fields 用法
logrusFields
log.Fatalf("Failed to send event %s to topic %s with key %d", event, topic, key)
logruslogrus
log.WithFields(log.Fields{
"event": event,
"topic": topic,
"key": key,
}).Fatal("Failed to send event")
前面的 WithFields API 可以规范使用者按照其提倡的方式记录日志.但是 WithFields 依然是可选的,因为某些场景下,使用者确实只需要记录仪一条简单的消息.
request_iduser_ip
requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})
requestLogger.Info("something happened on that request") # will log request_id and user_ip
requestLogger.Warn("something not great happened")
4.Hook 接口用法
logrus 最令人心动的功能就是其可扩展的 HOOK 机制了,通过在初始化时为 logrus 添加 hook,logrus 可以实现各种扩展功能.
logrus 的 hook 接口定义如下,其原理是每此写入日志时拦截,修改 logrus.Entry.
// logrus在记录Levels()返回的日志级别的消息时会触发HOOK,
// 按照Fire方法定义的内容修改logrus.Entry.
type Hook interface {
Levels() []Level
Fire(*Entry) error
}
一个简单自定义 hook 如下,DefaultFieldHook 定义会在所有级别的日志消息中加入默认字段 appName=”myAppName”.
type DefaultFieldHook struct {
}
func (hook *DefaultFieldHook) Fire(entry *log.Entry) error {
entry.Data["appName"] = "MyAppName"
return nil
}
func (hook *DefaultFieldHook) Levels() []log.Level {
return log.AllLevels
}
hooklog.AddHook(hook)hook
logrussysloghookhookHOOK
4.1 Logrus-Hook-Email
emailNewMailAuthHookhook
func Email(){
logger:= logrus.New()
//parameter"APPLICATION_NAME", "HOST", PORT, "FROM", "TO"
//首先开启smtp服务,最后两个参数是smtp的用户名和密码
hook, err := logrus_mail.NewMailAuthHook("testapp", "smtp.163.com",25,"username@163.com","username@163.com","smtp_name","smtp_password")
if err == nil {
logger.Hooks.Add(hook)
}
//生成*Entry
var filename="123.txt"
contextLogger :=logger.WithFields(logrus.Fields{
"file":filename,
"content": "GG",
})
//设置时间戳和message
contextLogger.Time=time.Now()
contextLogger.Message="这是一个hook发来的邮件"
//只能发送Error,Fatal,Panic级别的log
contextLogger.Level=logrus.FatalLevel
//使用Fire发送,包含时间戳,message
hook.Fire(contextLogger)
}
4.2 Logrus-Hook-Slack
github.com/johntdyer/slackrus
package main
import (
logrus "github.com/sirupsen/logrus"
"github.com/johntdyer/slackrus"
"os"
)
func main() {
logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.SetOutput(os.Stderr)
logrus.SetLevel(logrus.DebugLevel)
logrus.AddHook(&slackrus.SlackrusHook{
HookURL: "https://hooks.slack.com/services/abc123/defghijklmnopqrstuvwxyz",
AcceptedLevels: slackrus.LevelThreshold(logrus.DebugLevel),
Channel: "#slack-testing",
IconEmoji: ":ghost:",
Username: "foobot",
})
logrus.Warn("warn")
logrus.Info("info")
logrus.Debug("debug")
}
- HookURL: 填写 slack web-hook 地址
- AcceptedLevels: 设置日志输出级别
- Channel: 设置日志频道
- Username: 设置需要@的用户名
4.3 Logrus-Hook 日志分隔
logrus 本身不带日志本地文件分割功能,但是我们可以通过 file-rotatelogs 进行日志本地文件分割. 每次当我们写入日志的时候,logrus 都会调用 file-rotatelogs 来判断日志是否要进行切分.关于本地日志文件分割的例子网上很多,这里不再详细介绍,奉上代码:
import (
"github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
log "github.com/sirupsen/logrus"
"time"
)
func newLfsHook(logLevel *string, maxRemainCnt uint) log.Hook {
writer, err := rotatelogs.New(
logName+".%Y%m%d%H",
// WithLinkName为最新的日志建立软连接,以方便随着找到当前日志文件
rotatelogs.WithLinkName(logName),
// WithRotationTime设置日志分割的时间,这里设置为一小时分割一次
rotatelogs.WithRotationTime(time.Hour),
// WithMaxAge和WithRotationCount二者只能设置一个,
// WithMaxAge设置文件清理前的最长保存时间,
// WithRotationCount设置文件清理前最多保存的个数.
//rotatelogs.WithMaxAge(time.Hour*24),
rotatelogs.WithRotationCount(maxRemainCnt),
)
if err != nil {
log.Errorf("config local file system for logger error: %v", err)
}
level, ok := logLevels[*logLevel]
if ok {
log.SetLevel(level)
} else {
log.SetLevel(log.WarnLevel)
}
lfsHook := lfshook.NewHook(lfshook.WriterMap{
log.DebugLevel: writer,
log.InfoLevel: writer,
log.WarnLevel: writer,
log.ErrorLevel: writer,
log.FatalLevel: writer,
log.PanicLevel: writer,
}, &log.TextFormatter{DisableColors: true})
return lfsHook
}
使用上述本地日志文件切割的效果如下:
4.4 Logrus-Dingding-Hook 阿里钉钉群机器人
钉钉开发文档自定义机器人[2]
自定义 hook 代码 `utils/logrus_hook_dingding.go`[3]
可以无视的方法(异步发送 http json body 到钉钉 api 加快响应速度)
hook.jsonBodieshook.closeChanfunc (dh *dingHook) startDingHookQueueJob()func (dh *dingHook) Fire2(e *logrus.Entry) error
package utils
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/sirupsen/logrus"
)
var allLvls = []logrus.Level{
logrus.DebugLevel,
logrus.InfoLevel,
logrus.WarnLevel,
logrus.ErrorLevel,
logrus.FatalLevel,
logrus.PanicLevel,
}
func NewDingHook(url, app string, thresholdLevel logrus.Level) *dingHook {
temp := []logrus.Level{}
for _, v := range allLvls {
if v <= thresholdLevel {
temp = append(temp, v)
}
}
hook := &dingHook{apiUrl: url, levels: temp, appName: app}
hook.jsonBodies = make(chan []byte)
hook.closeChan = make(chan bool)
//开启chan 队列 执行post dingding hook api
go hook.startDingHookQueueJob()
return hook
}
func (dh *dingHook) startDingHookQueueJob() {
for {
select {
case return
case bs := res, err := http.Post(dh.apiUrl, "application/json", bytes.NewBuffer(bs))
if err != nil {
log.Println(err)
}
if res != nil && res.StatusCode != 200 {
log.Println("dingHook go chan http post error", res.StatusCode)
}
}
}
}
type dingHook struct {
apiUrl string
levels []logrus.Level
appName string
jsonBodies chan []byte
closeChan chan bool
}
// Levels sets which levels to sent to slack
func (dh *dingHook) Levels() []logrus.Level {
return dh.levels
}
//Fire2 这个异步有可能导致 最后一条消息丢失,main goroutine 提前结束到导致 子线程http post 没有发送
func (dh *dingHook) Fire2(e *logrus.Entry) error {
msg, err := e.String()
if err != nil {
return err
}
dm := dingMsg{Msgtype: "text"}
dm.Text.Content = fmt.Sprintf("%s \n %s", dh.appName, msg)
bs, err := json.Marshal(dm)
if err != nil {
return err
}
dh.jsonBodies return nil
}
func (dh *dingHook) Fire(e *logrus.Entry) error {
msg, err := e.String()
if err != nil {
return err
}
dm := dingMsg{Msgtype: "text"}
dm.Text.Content = fmt.Sprintf("%s \n %s", dh.appName, msg)
bs, err := json.Marshal(dm)
if err != nil {
return err
}
res, err := http.Post(dh.apiUrl, "application/json", bytes.NewBuffer(bs))
if err != nil {
return err
}
if res != nil && res.StatusCode != 200 {
return fmt.Errorf("dingHook go chan http post error %d", res.StatusCode)
}
return nil
}
type dingMsg struct {
Msgtype string `json:"msgtype"`
Text struct {
Content string `json:"content"`
} `json:"text"`
}
使用钉钉 hook `cmd/root.go`[4]
func initSlackLogrus() {
lvl := logrus.InfoLevel
//钉钉群机器人API地址
apiUrl := viper.GetString("logrus.dingHookUrl")
dingHook := utils.NewDingHook(apiUrl, "Felix", lvl)
logrus.SetLevel(lvl)
logrus.SetFormatter(&logrus.JSONFormatter{TimestampFormat: "06-01-02T15:04:05"})
logrus.SetReportCaller(true)
logrus.AddHook(dingHook)
}
logrus 线程安全
默认的 logger 在并发写的时候是被 mutex 保护的,比如当同时调用 hook 和写 log 时 mutex 就会被请求,有另外一种情况,文件是以 appending mode 打开的, 此时的并发操作就是安全的,可以用 logger.SetNoLock()来关闭它
致谢
- logrus[5]
- logrus-hook-email[6]
- logrus-hook-slack[7]
- logrus-hook-钉钉[8]
参考资料 [1]原文链接:https://mojotv.cn/2018/12/27/golang-logrus-tutorial
dejavuzhou/ginbro
[2]
钉钉开发文档自定义机器人: https://open-doc.dingtalk.com/microapp/serverapi2/qf2nxq
[3]utils/logrus_hook_dingding.go
[4]
cmd/root.go
[5]
logrus: https://github.com/sirupsen/logrus
[6]logrus-hook-email: https://github.com/zbindenren/logrus_mail
[7]logrus-hook-slack: https://github.com/johntdyer/slackrus
[8]logrus-hook-钉钉: https://github.com/dandans-dan/dingrus
推荐阅读
Go 每日一库之 Uber 开源的优秀日志库 zap