12 Star 145 Fork 20

aurora-engine/aurora

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
logger.go 2.22 KB
一键复制 编辑 原始数据 按行查看 历史
aurora.io 提交于 2023-08-30 14:38 +08:00 . gobatis aurora 日志统一替换为 zap 日志
package aurora
import (
"fmt"
"gitee.com/aurora-engine/web"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"net"
"os"
"strings"
"time"
)
var (
defaultLogger *zap.Logger
)
func init() {
// 自定义zap日志配置
encoderConfig := zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "logger",
CallerKey: "line",
MessageKey: "message",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder, // 小写编码器
EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format(time.DateTime))
},
EncodeDuration: zapcore.SecondsDurationEncoder, //
EncodeCaller: zapcore.ShortCallerEncoder, // 全路径编码器
EncodeName: zapcore.FullNameEncoder,
}
cfg := zap.Config{
Encoding: "console",
Level: zap.NewAtomicLevelAt(zap.DebugLevel),
OutputPaths: []string{"stdout"},
ErrorOutputPaths: []string{"stderr"},
EncoderConfig: encoderConfig,
}
var err error
defaultLogger, err = cfg.Build()
if err != nil {
panic(err)
}
}
func Log() web.Interceptor {
return &DefaultLogger{}
}
type DefaultLogger struct {
}
func (logger *DefaultLogger) Before(ctx web.Context, handler any) (bool, error) {
ctx["AuroraStartTime20230516"] = time.Now()
return true, nil
}
func (logger *DefaultLogger) Complete(ctx web.Context, handler any) error {
return nil
}
func (logger *DefaultLogger) After(ctx web.Context, handler any) error {
start := ctx["AuroraStartTime20230516"].(time.Time)
sub := time.Now().Sub(start).String()
r := ctx.Request()
url := r.URL.Path
method := r.Method
// 尝试从 X-Forwarded-For 中获取
xForwardedFor := r.Header.Get(`X-Forwarded-For`)
ip := strings.TrimSpace(strings.Split(xForwardedFor, `,`)[0])
if ip == `` {
// 尝试从 X-Real-Ip 中获取
ip = strings.TrimSpace(r.Header.Get(`X-Real-Ip`))
if ip == `` {
// 直接从 Remote Addr 中获取
_ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
if err != nil {
panic(err)
} else {
ip = _ip
}
}
}
info := fmt.Sprintf("| %3d | %s | %s | %s | %s\n", ctx.Status(), sub, ip, method, url)
fmt.Fprint(os.Stdout, info)
return nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/aurora-engine/aurora.git
git@gitee.com:aurora-engine/aurora.git
aurora-engine
aurora
aurora
v1.3.24

搜索帮助