lormatter/formatter.go

93 lines
1.9 KiB
Go

package lormatter
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/sirupsen/logrus"
)
var (
workspace string // 工作目录
)
func init() {
workspace, _ = os.Getwd()
workspace = filepath.ToSlash(workspace)
}
// Formatter implements logrus.Formatter interface.
type Formatter struct {
ShowTime bool // show time
ShowFile bool // show file name and line
ShowFunc bool // show func name when call
ShowField bool // show custom field
TimeLayout string // time layout
}
func (f *Formatter) shortLevel(level logrus.Level) string {
switch level {
case logrus.DebugLevel:
return "DEBU"
case logrus.InfoLevel:
return "INFO"
case logrus.WarnLevel:
return "WARN"
case logrus.ErrorLevel:
return "ERRO"
case logrus.FatalLevel:
return "FATAL"
case logrus.PanicLevel:
return "PANIC"
default:
return "INFO"
}
}
// Format building log message.
func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error) {
var builder bytes.Buffer
if f.ShowTime {
if f.TimeLayout == "" {
f.TimeLayout = time.DateTime
}
builder.WriteString(entry.Time.Format(f.TimeLayout))
builder.WriteString(" ")
}
if f.ShowFile {
content := fmt.Sprintf("[%s:%d] ", strings.ReplaceAll(entry.Caller.File, workspace, "."),
entry.Caller.Line)
builder.WriteString(content)
}
if f.ShowFunc {
s := strings.Split(entry.Caller.Function, ".")
content := fmt.Sprintf("[%s()] ", s[len(s)-1])
builder.WriteString(content)
}
builder.WriteString("[" + f.shortLevel(entry.Level) + "] ")
if f.ShowField {
for k, val := range entry.Data {
builder.WriteString(fmt.Sprintf("[%s=%v] ", k, val))
}
}
builder.WriteString(entry.Message)
builder.WriteRune('\n')
return builder.Bytes(), nil
}
// Register auto set formatter object for logrus.
func (f *Formatter) Register() {
logrus.SetFormatter(f)
logrus.SetReportCaller(true)
}