当前位置:网站首页>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就可以了
边栏推荐
- 用命令行 给 apk 签名
- 【Flask】Flask启程与实现一个基于Flask的最小应用程序
- Blind box NFT digital collection platform system development (build source code)
- [安网杯 2021] REV WP
- Understand the window query function of tdengine in one article
- 1.8新特性-List
- LeetCode重建二叉树详解[通俗易懂]
- Spark source code reading outline
- 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?
- String input function
猜你喜欢

Dragon lizard community open source coolbpf, BPF program development efficiency increased 100 times

Kongsong (Xintong Institute) - cloud security capacity building and trend in the digital era

SAP intelligent robot process automation (IRPA) solution sharing

北斗通信模块 北斗gps模块 北斗通信终端DTU
![[241. Design priority for operation expression]](/img/72/29d27204d5213a8efdb2c5be925dec.png)
[241. Design priority for operation expression]

04-Redis源码数据结构之字典

Liu Dui (fire line safety) - risk discovery in cloudy environment

Google Earth Engine(GEE)——全球人类居住区网格数据 1975-1990-2000-2014 (P2016)

Qtdeisgner, pyuic detailed use tutorial interface and function logic separation (nanny teaching)

焱融看 | 混合云时代下,如何制定多云策略
随机推荐
Research Report on China's software outsourcing industry investment strategy and the 14th five year plan Ⓡ 2022 ~ 2028
刘对(火线安全)-多云环境的风险发现
spark源码(五)DAGScheduler TaskScheduler如何配合提交任务,application、job、stage、taskset、task对应关系是什么?
终端识别技术和管理技术
Analysis report on the development prospect and investment strategic planning of China's wafer manufacturing Ⓔ 2022 ~ 2028
SAP 智能机器人流程自动化(iRPA)解决方案分享
Animesr: learnable degradation operator and new real world animation VSR dataset
Benefiting from the Internet, the scientific and technological performance of overseas exchange volume has returned to high growth
Content Audit Technology
Word2vec training Chinese word vector
Listen in the network
1.8 new features list
Have you ever encountered the problem that flynk monitors the PostgreSQL database and checkpoints cannot be used
洞态在某互联⽹⾦融科技企业的最佳落地实践
Investment analysis and prospect prediction report of global and Chinese p-nitrotoluene industry Ⓙ 2022 ~ 2027
受益互联网出海 汇量科技业绩重回高增长
China NdYAG crystal market research conclusion and development strategy proposal report Ⓥ 2022 ~ 2028
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?
9. Use of better scroll and ref
【Flask】Flask启程与实现一个基于Flask的最小应用程序