当前位置:网站首页>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.
边栏推荐
- How much money do novices prepare to play futures? Is agricultural products OK?
- 佩服,阿里女程序卧底 500 多个黑产群……
- 【241. 为运算表达式设计优先级】
- Applet - multiple text line breaks in view
- 龙蜥社区开源 coolbpf,BPF 程序开发效率提升百倍
- Simplex, half duplex, full duplex, TDD and FDD
- 用命令行 给 apk 签名
- 2022上半年英特尔有哪些“硬核创新”?看这张图就知道了!
- 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?
- 3.4 data query in introduction to database system - select (single table query, connection query, nested query, set query, multi table query)
猜你喜欢

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

玩转gRPC—不同编程语言间通信

A new book by teacher Zhang Yujin of Tsinghua University: 2D vision system and image technology (five copies will be sent at the end of the article)

2022 · 让我带你Jetpack架构组件从入门到精通 — Lifecycle

Self cultivation of open source programmers who contributed tens of millions of lines of code to shardingsphere and later became CEO

Enter the top six! Boyun's sales ranking in China's cloud management software market continues to rise

SAP 智能机器人流程自动化(iRPA)解决方案分享

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

How will the surging tide of digitalization overturn the future?

日志中打印统计信息的方案
随机推荐
Realize queue with stack and stack with queue (C language \leetcode\u 232+225)
Chen Yu (Aqua) - Safety - & gt; Cloud Security - & gt; Multicloud security
Explain IO multiplexing, select, poll, epoll in detail
一文读懂TDengine的窗口查询功能
SWT/ANR问题--如何捕获性能的trace
分布式事务简介(seata)
基于算力驱动、数据与功能协同的分布式动态(协同)渲染/功能运行时
2. Sensor size "recommended collection"
GET请求如何传递数组参数
Station B was scolded on the hot search..
建立自己的网站(21)
【 剑指 Offer】55 - I. 二叉树的深度
队列的基本操作(C语言实现)
Applet - applet chart Library (F2 chart Library)
介绍一种对 SAP GUI 里的收藏夹事务码管理工具增强的实现方案
French Data Protection Agency: using Google Analytics or violating gdpr
LeetCode重建二叉树详解[通俗易懂]
SAP intelligent robot process automation (IRPA) solution sharing
运行游戏时出现0xc000007b错误的解决方法[通俗易懂]
C language course design topic