当前位置:网站首页>Go整合Logrus实现日志打印
Go整合Logrus实现日志打印
2022-07-01 13:37:00 【Barry Yan】
Github:https://github.com/sirupsen/logrus
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就可以了
边栏推荐
- The stack size specified is too small, specify at least 328k
- Arthas use
- Fiori 应用通过 Adaptation Project 的增强方式分享
- 一文读懂TDengine的窗口查询功能
- Liu Dui (fire line safety) - risk discovery in cloudy environment
- Report on the "14th five year plan" and scale prospect prediction of China's laser processing equipment manufacturing industry Ⓢ 2022 ~ 2028
- 龙蜥社区开源 coolbpf,BPF 程序开发效率提升百倍
- Spark source code reading outline
- [machine learning] VAE variational self encoder learning notes
- 2. Sensor size "recommended collection"
猜你喜欢

Station B was scolded on the hot search..

Animesr: learnable degradation operator and new real world animation VSR dataset

内容审计技术

Summary of interview questions (1) HTTPS man in the middle attack, the principle of concurrenthashmap, serialVersionUID constant, redis single thread,

详细讲解面试的 IO多路复用,select,poll,epoll

Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud

B站被骂上了热搜。。
![[anwangbei 2021] Rev WP](/img/98/ea5c241e2b8f3ae4c76e1c75c9e0d1.png)
[anwangbei 2021] Rev WP

La taille de la pile spécifiée est petite, spécifiée à la sortie 328k

Self cultivation of open source programmers who contributed tens of millions of lines of code to shardingsphere and later became CEO
随机推荐
Google Earth engine (GEE) - Global Human Settlements grid data 1975-1990-2000-2014 (p2016)
Self cultivation of open source programmers who contributed tens of millions of lines of code to shardingsphere and later became CEO
盲盒NFT数字藏品平台系统开发(搭建源码)
北斗通信模块 北斗gps模块 北斗通信终端DTU
[sword finger offer] 55 - I. depth of binary tree
Collation and review of knowledge points of Microcomputer Principle and interface technology - pure manual
Application of 5g industrial gateway in scientific and technological overload control; off-site joint law enforcement for over limit, overweight and overspeed
Sign APK with command line
Build a vc2010 development environment and create a tutorial of "realizing Tetris game in C language"
JVM有哪些类加载机制?
Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
ArrayList capacity expansion mechanism and thread safety
Grafana reports an error: error= "failed to send notification to email addresses: [email protected] : 535 Error:
Declare an abstract class vehicle, which contains the private variable numofwheel and the public functions vehicle (int), horn (), setnumofwheel (int) and getnumofwheel (). Subclass mot
3.4 《数据库系统概论》之数据查询—SELECT(单表查询、连接查询、嵌套查询、集合查询、多表查询)
【剑指Offer】54. 二叉搜索树的第k大节点
Analysis report on the development prospect and investment strategy of the global and Chinese laser chip industry Ⓑ 2022 ~ 2027
【剑指 Offer】55 - II. 平衡二叉树
微机原理与接口技术知识点整理复习–纯手打
Leetcode第一题:两数之和(3种语言)