当前位置:网站首页>Go integrates logrus to realize log printing
Go integrates logrus to realize log printing
2022-07-01 13:56:00 【Barry Yan】
Github:https://github.com/sirupsen/logrus
1 Preliminary use
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 labeling 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 Configure common parameters
package main
import (
"context"
"github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
"os"
)
func main() {
method2()
}
func init() {
// Log as JSON Not the default ASCII Formatter .
log.SetFormatter(&log.JSONFormatter{
})
// Output to standard output , It could be anything io.Writer
log.SetOutput(os.Stdout)
// Record only xx Level or above
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 There are generally two kinds :
- &log.JSONFormatter{}
- &log.TextFormatter{}
There are seven log levels :
- log.Trace()
- log.Debug()
- log.Info()
- log.Warn()
- log.Error()
- log.Fatal()
- log.Panic()
4 Output log to file
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 The content of the document :
time="2022-01-06T13:04:25+08:00" level=info msg="This is a file log" filename=123.txt\
5 utilize Hooks Output logs to other places
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() {
// Use the airlock hook to report errors of severity or above an anomaly trace . You can create custom hooks , See the hook section .
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)
}
}
Only need AddHook Yes, add the corresponding Hook That's all right.
边栏推荐
- 进入前六!博云在中国云管理软件市场销量排行持续上升
- 程序设计的基本概念
- 自定义注解实现验证信息的功能
- Liu Dui (fire line safety) - risk discovery in cloudy environment
- 1.8 new features list
- User defined annotation realizes the function of verifying information
- So programmers make so much money doing private work? It's really delicious
- Chen Yu (Aqua) - Safety - & gt; Cloud Security - & gt; Multicloud security
- 清华章毓晋老师新书:2D视觉系统和图像技术(文末送5本)
- 介绍一种对 SAP GUI 里的收藏夹事务码管理工具增强的实现方案
猜你喜欢
![[anwangbei 2021] Rev WP](/img/98/ea5c241e2b8f3ae4c76e1c75c9e0d1.png)
[anwangbei 2021] Rev WP

日志中打印统计信息的方案

洞态在某互联⽹⾦融科技企业的最佳落地实践

【241. 为运算表达式设计优先级】

TexStudio使用教程
![[machine learning] VAE variational self encoder learning notes](/img/38/3eb8d9078b2dcbe780430abb15edcb.png)
[machine learning] VAE variational self encoder learning notes

Station B was scolded on the hot search..

Spark source code (V) how does dagscheduler taskscheduler cooperate with submitting tasks, and what is the corresponding relationship between application, job, stage, taskset, and task?

After being laid off for three months, the interview ran into a wall everywhere, and the mentality has begun to collapse

介绍一种对 SAP GUI 里的收藏夹事务码管理工具增强的实现方案
随机推荐
MySQL日志
So programmers make so much money doing private work? It's really delicious
QT社团管理系统
20个实用的 TypeScript 单行代码汇总
How will the surging tide of digitalization overturn the future?
开源实习经验分享:openEuler软件包加固测试
小程序- view中多个text换行
【IoT毕设.下】STM32+机智云AIoT+实验室安全监控系统
那个很努力的学生,高考失败了……别慌!你还有一次逆袭机会!
Self cultivation of open source programmers who contributed tens of millions of lines of code to shardingsphere and later became CEO
Several models of IO blocking, non blocking, IO multiplexing, signal driven and asynchronous IO
我们该如何保护自己的密码?
Understand the window query function of tdengine in one article
Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
分布式事务简介(seata)
B站被骂上了热搜。。
用命令行 给 apk 签名
ArrayList capacity expansion mechanism and thread safety
Enter the top six! Boyun's sales ranking in China's cloud management software market continues to rise
一文读懂TDengine的窗口查询功能