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
- 參考資料
程式碼倉庫://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: //github.com/sirupsen/logrus
logrus自定義日誌輸出格式: //blog.csdn.net/qmhball/article/details/116653565
logrus中輸出文件名、行號及函數名: //blog.csdn.net/qmhball/article/details/116656368