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 ...
随机推荐
- python语法缩进
1.python会根据缩进来判断代码行和前一句代码行之间的关系 2.for循环后一定要缩进,for循环后面的冒号代表告诉python,下面是代码行缩进的第一行
- python网络爬虫-python基础(三)
python安装 Anaconda的python科学计算环境,只需要想普通软件一样安装就可以把python的环境变量.解释器.开发环境都安装到计算机中 除此之外anaconda还提供众多的科学计算的包 ...
- 计算机电子书 2016 BiliDrive 备份
下载方式 根据你的操作系统下载不同的 BiliDrive 二进制. 执行: bilidrive download <link> 链接 文档 链接 Go入门指南.epub (1.87 MB) ...
- 「JOISC 2016 Day 1」棋盘游戏
「JOISC 2016 Day 1」棋盘游戏 先判无解:第1,3行有连续的空格或四个角有空格. 然后可以发现有解的情况第1,3行可以在任意时间摆放. 对于某一列,若第2行放有棋子,那么显然可以把棋盘分 ...
- 认识Html DOM
1.认识HTML DOM HTML Document Object Model 即:超文本标记语言-文档对象模型 HTML DOM理解为网页的API.它将网页中的各个元素都看作一个个对象,从而使网页中 ...
- python继承关系中,类属性的修改
class Grandfather(object): mylist = [] def __init__(self): pass class Father(Grandfather): pass Gran ...
- 7、前端--jQuery简介、基本选择器、基本筛选器、属性选择器、表单选择器、筛选器方法、节点操作、绑定事件
jQuery简介 宗旨:Write less, do more. 内部封装了js代码 是编程更加简单并且兼容所有的主流浏览器 版本:1.x 2.x 3.x # 可以使用3.x最新版 是第三方的类库:使 ...
- 1、架构--架构图、Iptables(简介、四表五链、流程图、使用、扩展模块)、包过滤防火墙
笔记 1.画架构图 2.Iptables 1.1 什么是防火墙 防止别人恶意访问. 1.2 防火墙种类 硬件防火墙 F5 软件防火墙 iptables firewalld 安全组 3.Iptables ...
- Solution -「CF 555E」Case of Computer Network
\(\mathcal{Description}\) Link. 给定 \(n\) 个点 \(m\) 条边的无向图,判断是否有给每条边定向的方案,使得 \(q\) 组有序点对 \((s,t)\) ...
- c++ 拷贝构造函数、拷贝运算符、析构函数
拷贝构造函数.拷贝运算符.析构函数 拷贝构造函数.拷贝运算符.析构函数 定义行为像值的类 class HasPtr{ public: HasPtr(const string &s = stri ...