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
  • 参考资料
下面展示几个常用的字段
type TextFormatter struct {
DisableColors bool // 开启颜色显示

DisableTimestamp bool // 开启时间显示

TimestampFormat string // 自定义时间格式

QuoteEmptyFields bool //空字段括在引号中

CallerPrettyfier func(*runtime.Frame) (function string, file string) //用于自定义方法名和文件名的输出
}
下面展示几个常用的字段
type JSONFormatter struct {
TimestampFormat string // 自定义时间格式

DisableTimestamp bool // 开启时间显示

CallerPrettyfier func(*runtime.Frame) (function string, file string) //用于自定义方法名和文件名的输出

PrettyPrint bool //将缩进所有json日志
}
只需要实现该接口
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
}
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)
}
Test
- log
- formatter
- formatter.go
- log.go
- main.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
}
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...)
}
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

Original: https://www.cnblogs.com/xiaofua/p/15829747.html
Author: 小傅啊
Title: Go之Logrus用法入门

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/516462/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Golang Zap日志

    Zap日志解析 Config.yaml zap: level: ‘info’ #日志级别 format: ‘console’ #输出的级别,有console和json prefix…

    Go语言 2023年5月25日
    073
  • 使用 grpcurl 通过命令行访问 gRPC 服务

    如果环境不支持安装这种 GUI 客户端的话,那么有没有一种工具,类似于 curl 这样的,直接通过终端,在命令行发起请求呢? 答案肯定是有的,就是本文要介绍的 grpcurl。 首…

    Go语言 2023年5月25日
    085
  • 化整为零优化重用,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang函数的定义和使用EP07

    函数是基于功能或者逻辑进行聚合的可复用的代码块。将一些复杂的、冗长的代码抽离封装成多个代码片段,即函数,有助于提高代码逻辑的可读性和可维护性。不同于Python,由于 Go lan…

    Go语言 2023年5月25日
    050
  • Go语言实现线程安全访问队列

    这个例子用Go语言的包”container/list”实现一个线程安全访问的队列。其中不少细节耐人寻味,做出它则是花费了不少精力,找不到样例啊! Go语言的…

    Go语言 2023年5月29日
    051
  • 基于LSM的Key-Value数据库实现WAL篇

    上篇文章简单的实现了基于LSM数据库的初步版本,在该版本中如数据写入到内存表后但还未持久化到SSTable排序字符串表,此时正好程序崩溃,内存表中暂未持久化的数据将会丢失。 引入W…

    Go语言 2023年5月25日
    064
  • 为开源项目 go-gin-api 增加后台任务模块

    任务管理界面 (WEB) 任务调度器 任务执行器 小结 推荐阅读 任务管理界面 (WEB) 支持在 WEB 界面 中对任务进行管理,例如…

    Go语言 2023年5月25日
    0113
  • 十分钟学会Golang开发gRPC服务

    gRPC是Google发起的一个开源RPC框架,使用HTTP/2传输协议,使用Protocol Buffers编码协议,相比RESTful框架的程序性能提高不少,而且当前流行的编程…

    Go语言 2023年5月25日
    079
  • Go语言程序的命令行参数

    获取命令行参数是程序功能多样化的必要前提。 这个例子展示Go语言如何获得程序的命令行参数。 Go语言程序: // echoarg project main.go package m…

    Go语言 2023年5月29日
    056
  • golang常用库包:Go依赖注入(DI)工具-wire使用

    google 出品的依赖注入库 wire:https://github.com/google/wire 什么是依赖注入 依赖注入 ,英文全名是 dependency injecti…

    Go语言 2023年5月25日
    069
  • Golang接口型函数使用技巧

    什么是接口型函数?顾名思义接口函数指的是用函数实现接口,这样在调用的时候就会非常简便,这种方式适用于只有一个函数的接口。 这里以迭代一个map为例,演示这一实现的技巧。 常规接口实…

    Go语言 2023年5月25日
    059
  • 对不起,我错了,这代码不好写

    hello,大家好呀,我是小楼。 前几天不是写了这篇文章《发现一个开源项目优化点,点进来就是你的了》嘛。 文章介绍了Sentinl的自适应缓存时间戳算法,从原理到实现都手把手解读了…

    Go语言 2023年5月25日
    070
  • 这不会又是一个Go的BUG吧?

    hello,大家好呀,我是小楼。 最近我又双叒叕写了个BUG,一个线上服务死锁了,不过幸亏是个新服务,没有什么大影响。 出问题的是Go的读写锁,如果你是写Java的,不必划走,更要…

    Go语言 2023年5月25日
    077
  • 【golang详解】go语言GMP(GPM)原理和调度

    Goroutine调度是一个很复杂的机制,下面尝试用简单的语言描述一下Goroutine调度机制,想要对其有更深入的了解可以去研读一下源码。 首先介绍一下GMP什么意思: G &#…

    Go语言 2023年5月25日
    066
  • Go语言实践模式 – 函数选项模式(Functional Options Pattern)

    什么是函数选项模式 大家好,我是小白,有点黑的那个白。 最近遇到一个问题,因为业务需求,需要对接三方平台. 而三方平台提供的一些HTTP(S)接口都有统一的密钥生成规则要求. 为此…

    Go语言 2023年5月25日
    050
  • Go语言基础之并发

    并发是编程里面一个非常重要的概念,Go语言在语言层面天生支持并发,这也是Go语言流行的一个很重要的原因。 Go语言中的并发编程 并发与并行 并发:同一时间段内执行多个任务(你在用微…

    Go语言 2023年5月29日
    061
  • sqlx操作MySQL实战及其ORM原理

    sqlx是Golang中的一个知名三方库,其为Go标准库database/sql提供了一组扩展支持。使用它可以方便的在数据行与Golang的结构体、映射和切片之间进行转换,从这个角…

    Go语言 2023年5月25日
    072
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球