-
Notifications
You must be signed in to change notification settings - Fork 135
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Loading status checks…
Replace logrus with zap and remove it
1 parent
7452f80
commit 74c886f
Showing
6 changed files
with
86 additions
and
117 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,142 +1,112 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"os" | ||
"path" | ||
"time" | ||
|
||
"github.com/gin-gonic/gin" | ||
"github.com/sirupsen/logrus" | ||
"go.uber.org/zap" | ||
"go.uber.org/zap/zapcore" | ||
"gopkg.in/natefinch/lumberjack.v2" | ||
) | ||
|
||
var logger *zap.SugaredLogger | ||
|
||
const ( | ||
logFileMaxSize = 50 // 日志文件最大大小(MB) | ||
logFileMaxBackups = 10 // 最多保留的备份文件数量 | ||
logFileMaxAge = 7 // 日志文件最长保留天数 | ||
logFileCompress = false // 是否压缩备份文件 | ||
) | ||
|
||
func InitLogger() { | ||
// 创建 logs 目录 | ||
if dir, err := os.Getwd(); err == nil { | ||
logFilePath := dir + "/logs/" | ||
if err := os.MkdirAll(logFilePath, 0777); err != nil { | ||
panic("create log dir failed") | ||
} | ||
} | ||
createLogPath() | ||
|
||
// 初始化 zap logger | ||
initZapLogger() | ||
} | ||
|
||
// 定义 gin logger | ||
func initLoggerForGin() *logrus.Logger { | ||
logFilePath := "" | ||
// createLogPath 创建 logs 目录 | ||
func createLogPath() error { | ||
if dir, err := os.Getwd(); err == nil { | ||
logFilePath = dir + "/logs/" | ||
} | ||
if err := os.MkdirAll(logFilePath, 0777); err != nil { | ||
fmt.Println(err.Error()) | ||
} | ||
logFileName := "access.log" | ||
|
||
// 日志文件 | ||
fileName := path.Join(logFilePath, logFileName) | ||
if _, err := os.Stat(fileName); err != nil { | ||
if _, err := os.Create(fileName); err != nil { | ||
panic("create log file failed") | ||
logFilePath := dir + "/logs/" | ||
if err := os.MkdirAll(logFilePath, 0777); err != nil { | ||
panic("create log path failed: " + err.Error()) | ||
} | ||
} | ||
|
||
// 写入文件 | ||
src, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend) | ||
if err != nil { | ||
fmt.Println("err", err) | ||
} | ||
|
||
// 实例化 | ||
_logger := logrus.New() | ||
|
||
// 设置输出 | ||
_logger.SetOutput(src) | ||
// logger.Out = src | ||
|
||
// 设置日志级别 | ||
_logger.SetLevel(logrus.DebugLevel) | ||
|
||
// 设置日志格式 | ||
_logger.Formatter = &logrus.JSONFormatter{} | ||
|
||
return _logger | ||
return nil | ||
} | ||
|
||
// gin 文件日志 | ||
func LoggerToFile() gin.HandlerFunc { | ||
_logger := initLoggerForGin() | ||
return func(c *gin.Context) { | ||
logMap := make(map[string]any) | ||
|
||
// 开始时间 | ||
startTime := time.Now() | ||
logMap["startTime"] = startTime.Format("2006-01-02 15:04:05") | ||
|
||
// 处理请求 | ||
c.Next() | ||
|
||
// 结束时间 | ||
endTime := time.Now() | ||
logMap["endTime"] = endTime.Format("2006-01-02 15:04:05") | ||
|
||
// 执行时间 | ||
logMap["latencyTime"] = endTime.Sub(startTime).Microseconds() | ||
|
||
// 请求方式 | ||
logMap["reqMethod"] = c.Request.Method | ||
|
||
// 请求路由 | ||
logMap["reqUri"] = c.Request.RequestURI | ||
|
||
// 状态码 | ||
logMap["statusCode"] = c.Writer.Status() | ||
|
||
// 请求IP | ||
logMap["clientIP"] = c.ClientIP() | ||
|
||
// 请求 UA | ||
logMap["clientUA"] = c.Request.UserAgent() | ||
|
||
// 日志格式 | ||
// logJson, _ := json.Marshal(logMap) | ||
// _logger.Info(string(logJson)) | ||
|
||
_logger.WithFields(logrus.Fields{ | ||
"startTime": logMap["startTime"], | ||
"endTime": logMap["endTime"], | ||
"latencyTime": logMap["latencyTime"], | ||
"reqMethod": logMap["reqMethod"], | ||
"reqUri": logMap["reqUri"], | ||
"statusCode": logMap["statusCode"], | ||
"clientIP": logMap["clientIP"], | ||
"clientUA": logMap["clientUA"], | ||
}).Info() | ||
// getLogPath 获取 logs 目录 | ||
func getLogPath() string { | ||
if dir, err := os.Getwd(); err == nil { | ||
return dir + "/logs/" | ||
} | ||
return "" | ||
} | ||
|
||
// 定义 zap logger | ||
func initZapLogger() { | ||
fileWriteSyncer := getLogWriter() | ||
encoder := getEncoder() | ||
core := zapcore.NewCore(encoder, zapcore.NewMultiWriteSyncer(fileWriteSyncer, zapcore.AddSync(os.Stdout)), zapcore.DebugLevel) | ||
core := zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), zapcore.DebugLevel) | ||
|
||
_logger := zap.New(core) | ||
defer _logger.Sync() | ||
|
||
logger = _logger.Sugar() | ||
logger = zap.New(core).Sugar() | ||
} | ||
|
||
// getEncoder 获取 zap encoder | ||
func getEncoder() zapcore.Encoder { | ||
return zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig()) | ||
} | ||
|
||
func getLogWriter() zapcore.WriteSyncer { | ||
file, _ := os.Create("./logs/runtime.log") | ||
return zapcore.AddSync(file) | ||
// initGinLogger 初始化 gin logger | ||
func initGinLogger() *zap.Logger { | ||
logPath := getLogPath() | ||
logFileName := "access.log" | ||
|
||
// 日志文件 | ||
logFile := path.Join(logPath, logFileName) | ||
|
||
lumberJackLogger := &lumberjack.Logger{ | ||
Filename: logFile, | ||
MaxSize: logFileMaxSize, // 日志文件最大大小(MB) | ||
MaxBackups: logFileMaxBackups, // 最多保留的备份文件数量 | ||
MaxAge: logFileMaxAge, // 日志文件最长保留天数 | ||
Compress: logFileCompress, // 是否压缩备份文件 | ||
} | ||
writeSyncer := zapcore.AddSync(lumberJackLogger) | ||
|
||
encoderConfig := zap.NewProductionEncoderConfig() | ||
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder | ||
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder | ||
encoderConfig.EncodeCaller = nil | ||
encoderConfig.EncodeDuration = zapcore.SecondsDurationEncoder | ||
encoder := zapcore.NewConsoleEncoder(encoderConfig) | ||
|
||
core := zapcore.NewCore(encoder, writeSyncer, zapcore.InfoLevel) | ||
|
||
return zap.New(core, zap.AddCaller()) | ||
} | ||
|
||
// initServiceLogger 初始化服务日志 | ||
func initServiceLogger() gin.HandlerFunc { | ||
_logger := initGinLogger() | ||
return func(c *gin.Context) { | ||
start := time.Now() | ||
path := c.Request.URL.Path | ||
|
||
c.Next() | ||
|
||
_logger.Info( | ||
"request", | ||
zap.String("time", start.Format(time.RFC3339)), | ||
zap.String("method", c.Request.Method), | ||
zap.String("ip", c.ClientIP()), | ||
zap.String("user-agent", c.Request.UserAgent()), | ||
zap.String("path", path), | ||
zap.Int("status", c.Writer.Status()), | ||
zap.Duration("latency", time.Since(start)), | ||
) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters