首页 > 其他分享 >Go实现整合 Logrus 输出json格式日志

Go实现整合 Logrus 输出json格式日志

时间:2022-12-01 10:22:24浏览次数:67  
标签:log logrus WithFields sirupsen json func Go 日志 Logrus

学习与交流:Go语言技术微信群

商务合作加微信:LetsFeng

图片

goland 全家桶激活码,支持所有版本,支持所有系统

链接:http://web.52shizhan.cn/activity/s2abxc

提取码:GJF9B1DK

 

现在就开始你的Go语言学习之旅吧!人生苦短,let’s Go.


图片

图片

 

1 初步使用

package main
import (
   "context"
   "github.com/sirupsen/logrus"
)

func main() {
   method0()
}
func method0() {
   logger:= logrus.New()
   logger.Warning("This is a first log.")
   ctx := context.WithValue(context.Background(),"key","value")
   logger.Warning(ctx,"This is a second log.")
}

 

2 增加标签WithFields

package main
import (
   "context"
   "github.com/sirupsen/logrus"
)
func main() {
   method1()
}
func method1() {
   log.WithFields(log.Fields{
      "fieldKey": "fieldValue",
   }).Warning("This is a first field log.")

   log.WithFields(log.Fields{
      "fieldKey": "fieldValue",
      "fieldKey2": "fieldValue2",
   }).Warning("This is a second field log.")
}

 

3 配置常见参数

package main
import (
   "context"
   "github.com/sirupsen/logrus"
   log "github.com/sirupsen/logrus"
   "os"
)
func main() {
   method2()
}
func init() {
   // 日志作为JSON而不是默认的ASCII格式器.
   log.SetFormatter(&log.JSONFormatter{})

   // 输出到标准输出,可以是任何io.Writer
   log.SetOutput(os.Stdout)

   // 只记录xx级别或以上的日志
   log.SetLevel(log.TraceLevel)
}
func method2() {
   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!")
}

 

Formatter一般分为两种:

  • &log.JSONFormatter{}

  • &log.TextFormatter{}

日志级别一共七种:

  • log.Trace()

  • log.Debug()

  • log.Info()

  • log.Warn()

  • log.Error()

  • log.Fatal()

  • log.Panic()

 

4 输出日志到文件

package main
import (
    "context"
    "github.com/sirupsen/logrus"
    "os"
)
func main() {
    method4()
}
func method4() {
   var log = logrus.New()
   file ,err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
   if err == nil{
      log.Out = file
   }else{
      log.Info("Failed to log to file")
   }

   log.WithFields(logrus.Fields{
      "filename": "123.txt",
   }).Info("This is a file log")
}

 

logrus.log文件的内容:

time="2022-01-06T13:04:25+08:00" 
level=info 
msg="This is a file log" 
filename=123.txt\

 

5 利用Hooks将日志输出到其他地方

import (
  log "github.com/sirupsen/logrus"
  "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake"
  logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
  "log/syslog"
)
func init() {
  // 使用气闸挂钩来报告错误严重程度或以上的错误一个异常追踪。您可以创建自定义钩子,请参见钩子部分。
  log.AddHook(airbrake.NewHook(123, "xyz", "production"))

  hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
  if err != nil {
    log.Error("Unable to connect to local syslog daemon")
  } else {
    log.AddHook(hook)
  }
}

只需要在AddHook是添加相应的Hook就可以了

到此这篇关于Go实现整合Logrus实现日志打印的文章就介绍到这了

 

文章首发:https://www.jb51.net/article/253981.htm

 

 

 

更多相关Go语言的技术文章或视频教程,请关注本公众号获取并查看,感谢你的支持与信任!

标签:log,logrus,WithFields,sirupsen,json,func,Go,日志,Logrus
From: https://www.cnblogs.com/cheyunhua/p/16940592.html

相关文章

  • 每日一抄 Go语言模拟远程调用
    packagemainimport( "errors" "fmt" "time")//客户端请求和接收封装/*下面代码封装了向服务器请求数据,等待服务器返回数据,如果请求超时该函数还会处理超时逻辑......
  • golang流式编程
    https://blog.csdn.net/u012986012/article/details/126833564  借助一些设计模式、流式编程、函数编程的方法可以让我们的Golang代码更清晰优雅,本文中描述了在错误处......
  • Go-05 Golang中的运算符
    packagemainimport"fmt"/* Golang中的运算符 Golang内置的运算符: 1.算术运算符:+-*/% 2.关系运算符:!===>>=<<= 返回值是True或者False 3.逻辑运......
  • [15-445]Join Algorithms memo (Join 为什么要用小表做驱动表)
    NestedLoopJoin这一章节主要讲解join的算法,我想记录一些重点的地方。有趣的是关于NestedLoopjoin对驱动表为什么小表会更好这个问题,搜遍简中的blog都是一些错......
  • Installing golang-1.18 on openEuler
    一、Installinggolang-1.18onopenEulerhttps://golang.google.cn1下载mkdir/opt/software&&cd/opt/softwarewgethttps://golang.google.cn/dl/go1.18.linux......
  • Golang实现小型CMS内容管理功能(二):前端接入百度ueditor富文本编辑器
    当我们把接口都做好以后,我们需要去开发前端界面。添加文章功能里面,最重要的就是文章内容部分,需要配置上富文本编辑器,这样才能给我们的内容增加样式。 下载ueditor代码......
  • django-rest-framework(更新中)
    @目录(三十六)Web应用模式(三十七)API接口(三十八)Restful规范(三十九)drf安装和简单使用1、安装2、使用3、postman测试(四十)源码分析cbvAPIView源码分析补充:drf的Request类(三十六......
  • Google Chrome(谷歌浏览器)安装使用
    谷歌浏览器官网https://www.google.cn/chrome/ Chrome是由Google开发的一款简单便捷的网页浏览工具。谷歌浏览器(GoogleChrome)可以提帮助你快速、安全的搜索到自己需......
  • go redis v8 gin session
    今天使用到gin的模版功能,于是学习了一下登录session因为gin有自家开发好的sessionredis。所以在redis支持方面。已经有支持好的了但是看了一下golangredis方面,发现有......
  • 重构后台的django项目目录、配置开发环境、添加环境变量
    重构项目目录celery_task:logs:项目运行时/开发时日志目录包luffapi:项目同名文件夹apps:项目所有应用的集合文件夹libs:第三方类库的保存目录[第三方组件、模块]-包......