Go之Logrus用法入门
Go之Logrus用法入门
Logrus是Go (golang)的结构化日志程序,完全兼容标准库的API日志程序。
Logrus is a structured logger for Go (golang), completely API compatible with the standard library logger.
文章目录:
- Logrus自带两种formatter
- TextFormatter
- JsonFormatter
- 自定义Formatter
- Logrus基本用法
- 自定义Log
- 包结构
- formatter.go
- log.go
- main.go
- 参考资料
代码仓库:https://github.com/qo0581122/go-logrus-document
注意:基本用法请跳转Logrus
1 Logrus自带两种formatter
1.1 TextFormatter
下面展示几个常用的字段
type TextFormatter struct {
DisableColors bool // 开启颜色显示
DisableTimestamp bool // 开启时间显示
TimestampFormat string // 自定义时间格式
QuoteEmptyFields bool //空字段括在引号中
CallerPrettyfier func(*runtime.Frame) (function string, file string) //用于自定义方法名和文件名的输出
}
1.2 JsonFormatter
下面展示几个常用的字段
type JSONFormatter struct {
TimestampFormat string // 自定义时间格式
DisableTimestamp bool // 开启时间显示
CallerPrettyfier func(*runtime.Frame) (function string, file string) //用于自定义方法名和文件名的输出
PrettyPrint bool //将缩进所有json日志
}
1.3 第三种 自定义Formatter
只需要实现该接口
type Formatter interface {
Format(*Entry) ([]byte, error)
}
其中entry参数
type Entry struct {
// Contains all the fields set by the user.
Data Fields
// Time at which the log entry was created
Time time.Time
// Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic
Level Level
//Calling method, with package name
Caller *runtime.Frame
//Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic
Message string
//When formatter is called in entry.log(), a Buffer may be set to entry
Buffer *bytes.Buffer
}
2 Logrus基本用法
func Demo(log *logrus.Logger) {
log.Info("i'm demo")
}
func main() {
log := logrus.New()
log.SetReportCaller(true)
log.SetFormatter(&logrus.JSONFormatter{
TimestampFormat: "2006-01-02 15:03:04", //自定义日期格式
CallerPrettyfier: func(frame *runtime.Frame) (function string, file string) { //自定义Caller的返回
//处理文件名
fileName := path.Base(frame.File)
return frame.Function, fileName
},
})
Demo(log)
}
3 自定义Log
3.1 包结构
Test
- log
- formatter
- formatter.go
- log.go
- main.go
3.2 formatter.go
package formatter
import (
"bytes"
"fmt"
"path"
logrus "github.com/sirupsen/logrus"
)
//颜色
const (
red = 31
yellow = 33
blue = 36
gray = 37
)
type LogFormatter struct{}
//实现Formatter(entry *logrus.Entry) ([]byte, error)接口
func (t *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
//根据不同的level去展示颜色
var levelColor int
switch entry.Level {
case logrus.DebugLevel, logrus.TraceLevel:
levelColor = gray
case logrus.WarnLevel:
levelColor = yellow
case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:
levelColor = red
default:
levelColor = blue
}
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
//自定义日期格式
timestamp := entry.Time.Format("2006-01-02 15:04:05")
if entry.HasCaller() {
//自定义文件路径
funcVal := entry.Caller.Function
fileVal := fmt.Sprintf("%s:%d", path.Base(entry.Caller.File), entry.Caller.Line)
//自定义输出格式
fmt.Fprintf(b, "[%s] \x1b[%dm[%s]\x1b[0m %s %s %s\n", timestamp, levelColor, entry.Level, fileVal, funcVal, entry.Message)
} else {
fmt.Fprintf(b, "[%s] \x1b[%dm[%s]\x1b[0m %s\n", timestamp, levelColor, entry.Level, entry.Message)
}
return b.Bytes(), nil
}
3.3 log.go
package Log
import (
"os"
. "./formatter"
"github.com/sirupsen/logrus"
)
var Logger = NewLog()
type Log struct {
log *logrus.Logger
}
func NewLog() *Log {
mLog := logrus.New() //新建一个实例
mLog.SetOutput(os.Stderr) //设置输出类型
mLog.SetReportCaller(true) //开启返回函数名和行号
mLog.SetFormatter(&LogFormatter{}) //设置自己定义的Formatter
mLog.SetLevel(logrus.DebugLevel) //设置最低的Level
return &Log{
log: mLog,
}
}
//封装一些会用到的方法
func (l *Log) Debug(args ...interface{}) {
l.log.Debugln(args...)
}
func (l *Log) Debugf(format string, args ...interface{}) {
l.log.Debugf(format, args...)
}
func (l *Log) Info(args ...interface{}) {
l.log.Infoln(args...)
}
func (l *Log) Infof(format string, args ...interface{}) {
l.log.Infof(format, args...)
}
func (l *Log) Error(args ...interface{}) {
l.log.Errorln(args...)
}
func (l *Log) Errorf(format string, args ...interface{}) {
l.log.Errorf(format, args...)
}
func (l *Log) Trace(args ...interface{}) {
l.log.Traceln()
}
func (l *Log) Tracef(format string, args ...interface{}) {
l.log.Tracef(format, args...)
}
func (l *Log) Panic(args ...interface{}) {
l.log.Panicln()
}
func (l *Log) Panicf(format string, args ...interface{}) {
l.log.Panicf(format, args...)
}
func (l *Log) Print(args ...interface{}) {
l.log.Println()
}
func (l *Log) Printf(format string, args ...interface{}) {
l.log.Printf(format, args...)
}
3.4 main.go
package main
import (
. "./log"
)
func Demo() {
Logger.Info("i'm demo")
}
func main() {
Demo()
}
//输出,其中[info]为蓝色
[2022-01-21 10:10:47] [info] entry.go:359 github.com/sirupsen/logrus.(*Entry).Logln i'm demo
4 参考资料
logrus: https://github.com/sirupsen/logrus
logrus自定义日志输出格式: https://blog.csdn.net/qmhball/article/details/116653565
logrus中输出文件名、行号及函数名: https://blog.csdn.net/qmhball/article/details/116656368
Go之Logrus用法入门的更多相关文章
- 精通awk系列(4):awk用法入门
回到: Linux系列文章 Shell系列文章 Awk系列文章 awk用法入门 awk 'awk_program' a.txt awk示例: # 输出a.txt中的每一行 awk '{print $0 ...
- [转帖]PG语法解剖--基本sql语句用法入门
PG语法解剖--基本sql语句用法入门 https://www.toutiao.com/i6710897833953722894/ COPY 命令挺好的 需要学习一下. 原创 波波说运维 2019-0 ...
- AWK用法入门详解
简介 awk是一个强大的文本分析工具,相对于grep的查找,sed的编辑,awk在其对数据分析并生成报告时,显得尤为强大.简单来说awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再 ...
- MongoDB 用法入门(windows)①
概述 大家对数据库肯定不陌生,肯定也有很多人用过MySQL,但是在用MySQL的时候各种建表,写表之间的关联让人非常头疼. MongoDB也是一种数据库,但是它不是用表,而是用集合来装数据的,我对这种 ...
- LESS 用法入门
本文旨在加深对 LESS 的理解和记忆,供自己开发时参考.相信对没有接触过 LESS 的程序员还是有用的,大佬绕路. 一. 安装和使用 LESS 1.1 安装 使用命令行安装 LESS npm ins ...
- PriorityQueue优先队列用法入门
PriorityQueue是队列的一种,它叫做优先队列,该类实现了Queue接口. 之所以叫做优先队列,是因为PriorityQueue实现了Comparator这个比较接口,也就是PriorityQ ...
- jquery validate.js表单验证的基本用法入门
这里转载一篇前辈写的文章,在我自己的理解上修改了一下,仅作记录. 先贴一个国内某大公司的代码: 复制代码 代码如下: <script type="text/javascript&quo ...
- Swing-JComboBox用法-入门
JComboBox是Swing中的下拉菜单控件.它永远只能选中一个项目,然而比单选按钮节省空间.如果使用setEditable设置为true则内部选项的文本可以编辑,因此这种组件被称为组合框.注意,对 ...
- Swing-setBorder()用法-入门
注:本文内容转自:Swing编程边框(Border)的用法总结.内容根据笔者理解稍有整理. 函数说明: public void setBorder(Border border) 设置此组件的边框.Bo ...
随机推荐
- Vue2和Vue3技术整理1 - 入门篇 - 更新完毕
Vue2 0.前言 首先说明:要直接上手简单得很,看官网熟悉大概有哪些东西.怎么用的,然后简单练一下就可以做出程序来了,最多两天,无论Vue2还是Vue3,就都完全可以了,Vue3就是比Vue2多了一 ...
- Airtest 的连接安卓模拟器
1. 开启安卓模拟器 2. 查看进程,MEmuHeadless.exe的进行程号, 然后在cmd中输入 netstat -ano|findstr "16116" 3. 到 airt ...
- webpack学习:uni运行时代码解读一 (页面初始化加载)
uni的vue代码是如何在微信小程序里面执行的,对此比较感兴趣所以去调试学习了一波. 准备工作 // 在vue.config.js里打开非压缩的代码 module.exports = { config ...
- spring学习三:Spring Bean 生命周期
Bean 的生命周期 理解 Spring bean 的生命周期很容易.当一个 bean 被实例化时,它可能需要执行一些初始化使它转换成可用状态.同样,当 bean 不再需要,并且从容器中移除时,可能需 ...
- Android API在线网站
http://android-doc.com/reference/packages.html
- 出现Table ‘./mysql/proc’ is marked as crashed and should be repaired
一般这种表崩溃的问题出现在mysql异常停止,或者使用kill -9命令强行杀掉进程导致,进入MySQL命令行后,执行下面的命令即可修复'./mysql/proc'表 repair table mys ...
- HMS Core 能力速配,唱响恋爱进行曲
情人节,HMS Core 最具CP感的能力搭档来袭,浓浓爱意,表白各行业,你准备好了吗? 1.ML Kit +Signpal Kit 科技相助,恋爱提速.展现爱意的方式有千百种,你可以用文本翻译学习数 ...
- 海康PTZ云台摄像头调试之直接控制云台(C#)
众所周知,海康的摄像头sdk较为完善,但是对于新手来说还是有点麻烦. 今天写一篇随笔给大家展示下怎么控制海康摄像头的云台(前提是有ptz云台设备) 1.sdk准备 本文基于C#的frame来开发一个p ...
- 论文翻译:2022_PACDNN: A phase-aware composite deep neural network for speech enhancement
论文地址:PACDNN:一种用于语音增强的相位感知复合深度神经网络 引用格式:Hasannezhad M,Yu H,Zhu W P,et al. PACDNN: A phase-aware compo ...
- python进阶(25)协程
协程的定义 协程(Coroutine),又称微线程,纤程.(协程是一种用户态的轻量级线程) 作用:在执行 A 函数的时候,可以随时中断,去执行 B 函数,然后中断B函数,继续执行 A 函数 (可以自动 ...