From d464695b66547213b8c72ba3e0d669ac8e45eea5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=BA=90=E6=96=87=E9=9B=A8?= <41315874+fumiama@users.noreply.github.com> Date: Mon, 27 Dec 2021 16:51:53 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20win=20=E4=B8=8B=20log=20=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E9=A2=9C=E8=89=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main_win.go | 60 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 4 deletions(-) diff --git a/main_win.go b/main_win.go index e08a3719..2f1814f6 100644 --- a/main_win.go +++ b/main_win.go @@ -9,8 +9,60 @@ import ( ) func init() { - // windows 不支持带颜色的 log,故自定义格式 - logrus.SetFormatter(&easy.Formatter{ - LogFormat: "[%lvl%] %msg%\n", - }) + // windows 带颜色 log 自定义格式 + logrus.SetFormatter(&LogFormat{}) +} + +const ( + colorCodePanic = "\x1b[1;31m" // color.Style{color.Bold, color.Red}.String() + colorCodeFatal = "\x1b[1;31m" // color.Style{color.Bold, color.Red}.String() + colorCodeError = "\x1b[31m" // color.Style{color.Red}.String() + colorCodeWarn = "\x1b[33m" // color.Style{color.Yellow}.String() + colorCodeInfo = "\x1b[37m" // color.Style{color.White}.String() + colorCodeDebug = "\x1b[32m" // color.Style{color.Green}.String() + colorCodeTrace = "\x1b[36m" // color.Style{color.Cyan}.String() + colorReset = "\x1b[0m" +) + +// LogFormat specialize for zbp +type LogFormat struct{} + +// Format implements logrus.Formatter +func (f LogFormat) Format(entry *logrus.Entry) ([]byte, error) { + buf := new(bytes.Buffer) + + buf.WriteString(getLogLevelColorCode(entry.Level)) + + buf.WriteByte('[') + buf.WriteString(strings.ToUpper(entry.Level.String())) + buf.WriteString("]: ") + buf.WriteString(entry.Message) + buf.WriteString(" \n") + + buf.WriteString(colorReset) + + return buf.Bytes(), nil +} + +// getLogLevelColorCode 获取日志等级对应色彩code +func getLogLevelColorCode(level logrus.Level) string { + switch level { + case logrus.PanicLevel: + return colorCodePanic + case logrus.FatalLevel: + return colorCodeFatal + case logrus.ErrorLevel: + return colorCodeError + case logrus.WarnLevel: + return colorCodeWarn + case logrus.InfoLevel: + return colorCodeInfo + case logrus.DebugLevel: + return colorCodeDebug + case logrus.TraceLevel: + return colorCodeTrace + + default: + return colorCodeInfo + } }