当前位置:网站首页>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就可以了
边栏推荐
- Google Earth engine (GEE) - Global Human Settlements grid data 1975-1990-2000-2014 (p2016)
- Apache-atlas-2.2.0 independent compilation and deployment
- 详细讲解面试的 IO多路复用,select,poll,epoll
- Application of 5g industrial gateway in scientific and technological overload control; off-site joint law enforcement for over limit, overweight and overspeed
- When you really learn databinding, you will find "this thing is really fragrant"!
- 机器学习总结(一):线性回归、岭回归、Lasso回归
- 5. Use of ly tab plug-in of header component
- 小程序- view中多个text换行
- 【剑指 Offer】55 - II. 平衡二叉树
- Research Report on China's software outsourcing industry investment strategy and the 14th five year plan Ⓡ 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?

开源者的自我修养|为 ShardingSphere 贡献了千万行代码的程序员,后来当了 CEO

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

龙蜥社区开源 coolbpf,BPF 程序开发效率提升百倍

Station B was scolded on the hot search..

5G工业网关的科技治超应用 超限超重超速非现场联合执法

【机器学习】VAE变分自编码器学习笔记

Fiori 应用通过 Adaptation Project 的增强方式分享

04-Redis源码数据结构之字典
随机推荐
MySQL 66 questions, 20000 words + 50 pictures in detail! Necessary for review
一款Flutter版的记事本
5. Use of ly tab plug-in of header component
arthas使用
When you really learn databinding, you will find "this thing is really fragrant"!
受益互联网出海 汇量科技业绩重回高增长
[Jianzhi offer] 55 - ii balanced binary tree
Some summary of pyqt5 learning (overview of the general meaning of some signals and methods)
二传感器尺寸「建议收藏」
04-Redis源码数据结构之字典
小程序-小程序图表库(F2图表库)
面试题目总结(1) https中间人攻击,ConcurrentHashMap的原理 ,serialVersionUID常量,redis单线程,
[Jianzhi offer] 54 The k-th node of binary search tree
详细讲解面试的 IO多路复用,select,poll,epoll
北斗通信模块 北斗gps模块 北斗通信终端DTU
洞态在某互联⽹⾦融科技企业的最佳落地实践
Etcd summary mechanism and usage scenarios
20个实用的 TypeScript 单行代码汇总
运行游戏时出现0xc000007b错误的解决方法[通俗易懂]
10. Page layout, guess you like it