Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dependency:Use logrus instead of zap #26

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,9 @@ func Init(path string, service string) {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
logger.Fatal("config.Init: could not find config files")
} else {
logger.Fatal("config.Init: read config error: %v", err)
logger.Fatalf("config.Init: read config error: %v", err)
}
logger.Fatal("config.Init: read config error: %v", err)
logger.Fatalf("config.Init: read config error: %v", err)
}

configMapping(service)
Expand Down
10 changes: 5 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@ require (
github.com/redis/go-redis/v9 v9.6.1
github.com/sirupsen/logrus v1.9.3
github.com/spf13/viper v1.19.0
github.com/stretchr/testify v1.9.0
github.com/uber/jaeger-client-go v2.30.0+incompatible
github.com/west2-online/jwch v0.1.4
golang.org/x/sync v0.8.0
golang.org/x/time v0.7.0
gorm.io/driver/mysql v1.5.7
gorm.io/gorm v1.25.12
gorm.io/plugin/opentracing v0.0.0-20211220013347-7d2b2af23560
Expand Down Expand Up @@ -55,6 +58,7 @@ require (
github.com/nats-io/nuid v1.0.1 // indirect
github.com/nyaruka/phonenumbers v1.4.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/sagikazarmark/crypt v0.19.0 // indirect
github.com/sagikazarmark/locafero v0.6.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect
Expand All @@ -63,6 +67,7 @@ require (
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.55.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.55.0 // indirect
go.opentelemetry.io/otel/metric v1.30.0 // indirect
go.uber.org/zap v1.26.0 // indirect
golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20241007155032-5fefd90f89a9 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20241007155032-5fefd90f89a9 // indirect
Expand Down Expand Up @@ -126,11 +131,9 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/sagikazarmark/crypt v0.26.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.7.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/testify v1.9.0
github.com/subosito/gotenv v1.6.0 // indirect
github.com/tidwall/gjson v1.18.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
Expand All @@ -146,15 +149,12 @@ require (
go.opentelemetry.io/otel/trace v1.30.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0
golang.org/x/arch v0.11.0 // indirect
golang.org/x/crypto v0.28.0 // indirect
golang.org/x/net v0.30.0 // indirect
golang.org/x/oauth2 v0.23.0 // indirect
golang.org/x/sync v0.8.0
golang.org/x/sys v0.26.0 // indirect
golang.org/x/text v0.19.0 // indirect
golang.org/x/time v0.7.0
google.golang.org/api v0.200.0 // indirect
google.golang.org/genproto v0.0.0-20241007155032-5fefd90f89a9 // indirect
google.golang.org/grpc v1.67.1 // indirect
Expand Down
8 changes: 4 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -415,8 +415,8 @@ github.com/redis/go-redis/v9 v9.6.1/go.mod h1:0C0c6ycQsdpVNQpxb1njEQIqkx5UcsM8FJ
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sagikazarmark/crypt v0.26.0 h1:IgjeESCuBba4UsOyp375rvHNyQu6D3bJtRbpW3XqsTo=
github.com/sagikazarmark/crypt v0.26.0/go.mod h1:Gj2k5Df5aPaGm+zmfyijVKDeav5Om3KjjRiVodthJfk=
github.com/sagikazarmark/crypt v0.19.0 h1:WMyLTjHBo64UvNcWqpzY3pbZTYgnemZU8FBZigKc42E=
github.com/sagikazarmark/crypt v0.19.0/go.mod h1:c6vimRziqqERhtSe0MhIvzE1w54FrCHtrXb5NH/ja78=
github.com/sagikazarmark/locafero v0.6.0 h1:ON7AQg37yzcRPU69mt7gwhFEBwxI6P9T4Qu3N51bwOk=
github.com/sagikazarmark/locafero v0.6.0/go.mod h1:77OmuIc6VTraTXKXIs/uvUxKGUXjE1GbemJYHqdNjX0=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
Expand Down Expand Up @@ -531,8 +531,8 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.11.0 h1:KXV8WWKCXm6tRpLirl2szsO5j/oOODwZf4hATmGVNs4=
golang.org/x/arch v0.11.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
Expand Down
126 changes: 126 additions & 0 deletions pkg/logger/formatter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
Copyright 2024 The west2-online Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package logger

import (
"bytes"
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"

"github.com/sirupsen/logrus"
)

// MyFormatter 是一个自定义的日志格式化器,
type MyFormatter struct {
wd string
}

// Format 将日志条目格式化为字节切片。
// 它根据条目是否有调用者信息,决定写入哪些信息。
func (m *MyFormatter) Format(entry *logrus.Entry) ([]byte, error) {
b := entry.Buffer

// 如果有调用者信息,则写入时间戳、日志级别、简短调用者路径、消息和堆栈跟踪。
// 否则,只写入时间戳、日志级别、消息和堆栈跟踪。
if entry.HasCaller() {
writeTimestamp(b, entry)
writeLevel(b, entry)
writeShortCallerPath(b, entry)
writeMessage(b, entry)
writeCallerStack(b, entry)
writeLineBreak(b)
} else {
writeTimestamp(b, entry)
writeLevel(b, entry)
writeMessage(b, entry)
writeCallerStack(b, entry)
writeLineBreak(b)
}

return b.Bytes(), nil
}

func getNewFormatter() *MyFormatter {
wd, err := os.Getwd()
if err != nil {
panic(err)
}
return &MyFormatter{
wd,
}
}

func writeTimestamp(b *bytes.Buffer, entry *logrus.Entry) {
b.WriteString(entry.Time.Format(time.RFC3339))
b.WriteRune(' ')
}

func writeLevel(b *bytes.Buffer, entry *logrus.Entry) {
b.WriteRune('[')
b.WriteString(strings.ToUpper(entry.Level.String()))
b.WriteRune(']')
b.WriteRune(' ')
}

// writeShortCallerPath 将日志条目的调用者路径写入缓冲区。
// 它使用工作目录来构建一个更短的调用者路径。
func writeShortCallerPath(b *bytes.Buffer, entry *logrus.Entry) {
parts := strings.Split(entry.Caller.File, "/")
if len(parts) > 2 {
b.WriteString(filepath.Join(parts[len(parts)-2], parts[len(parts)-1])) // // 只使用文件名和最后一个目录。
} else {
b.WriteString(entry.Caller.File) // 如果路径太短,则直接使用完整路径。
}

b.WriteRune(':')
b.WriteString(strconv.Itoa(entry.Caller.Line))
b.WriteRune(' ')
}

func writeMessage(b *bytes.Buffer, entry *logrus.Entry) {
b.WriteString(entry.Message)
}

// writeCallerStack 如果日志级别大于等于 ErrorLevel,则将调用堆栈写入缓冲区。
func writeCallerStack(b *bytes.Buffer, entry *logrus.Entry) {
if entry.Level > logrus.ErrorLevel {
return
}
b.WriteString("\nStack Trace:\n")

pc := make([]uintptr, 10)
n := runtime.Callers(10, pc)
frames := runtime.CallersFrames(pc[:n-1])

for {
frame, more := frames.Next()
b.WriteString(fmt.Sprintf("%s\n", frame.Function))
b.WriteString(fmt.Sprintf(" %s:%d\n", frame.File, frame.Line))
if !more {
break
}
}
}

func writeLineBreak(b *bytes.Buffer) {
b.WriteRune('\n')
}
72 changes: 29 additions & 43 deletions pkg/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,52 +17,38 @@ limitations under the License.
package logger

import (
"io"
"os"
"sync"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/sirupsen/logrus"
)

var (
LoggerObj *zap.SugaredLogger
once sync.Once
LoggerObj *logrus.Logger
ErrLoggerObj *logrus.Logger
once sync.Once
)

// 初始化 Logger 的函数
// initLogger 初始化两个日志对象,一个用于普通日志输出,一个用于错误日志输出。
func initLogger() {
// 配置 zap 的日志等级和输出格式
config := zap.Config{
Level: zap.NewAtomicLevelAt(zap.DebugLevel), // 设置日志等级
Development: false, // 非开发模式
Encoding: "console", // 输出格式(json 或 console)
OutputPaths: []string{"stdout"}, // 输出目标
ErrorOutputPaths: []string{"stderr"}, // 错误输出目标
EncoderConfig: zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "logger",
CallerKey: "caller",
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.CapitalLevelEncoder, // 日志等级大写
EncodeTime: zapcore.ISO8601TimeEncoder, // 时间格式
EncodeDuration: zapcore.StringDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
},
}
logger, err := config.Build(zap.AddCallerSkip(1)) // 创建基础 Logger
if err != nil {
panic(err)
}

// 创建 SugaredLogger
LoggerObj = logger.Sugar()
logger := getBaseLogger(os.Stdout)
errLogger := getBaseLogger(os.Stderr)

ErrLoggerObj = errLogger
LoggerObj = logger
}

func getBaseLogger(output io.Writer) *logrus.Logger {
logger := logrus.New()
logger.SetReportCaller(true) // 设置日志记录器在日志条目中包含调用者信息。
logger.SetFormatter(getNewFormatter())
logger.SetLevel(logrus.DebugLevel) // 调整日志等级
logger.SetOutput(output)
return logger
}

// 确保 LoggerObj 只初始化一次
// 使用 init() 函数来替代 syncOnce 是个方法,而且不需要额外的代码来进行 check
// 但是这样损失了更多的 DIY 特性,比如可以在初始化的时候传入参数
func ensureLoggerInit() {
once.Do(func() {
initLogger()
Expand All @@ -71,12 +57,12 @@ func ensureLoggerInit() {

func Fatalf(template string, args ...interface{}) {
ensureLoggerInit()
LoggerObj.Fatalf(template, args...)
ErrLoggerObj.Fatalf(template, args...)
}

func Errorf(template string, args ...interface{}) {
ensureLoggerInit()
LoggerObj.Errorf(template, args...)
ErrLoggerObj.Errorf(template, args...)
}

func Infof(template string, args ...interface{}) {
Expand All @@ -91,20 +77,20 @@ func Debugf(template string, args ...interface{}) {

func Fatal(args ...interface{}) {
ensureLoggerInit()
LoggerObj.Fatal(args)
ErrLoggerObj.Fatal(args...)
}

func Info(args ...interface{}) {
func Error(args ...interface{}) {
ensureLoggerInit()
LoggerObj.Info(args)
ErrLoggerObj.Error(args...)
}

func Error(args ...interface{}) {
func Info(args ...interface{}) {
ensureLoggerInit()
LoggerObj.Error(args)
LoggerObj.Info(args...)
}

func Debug(args ...interface{}) {
ensureLoggerInit()
LoggerObj.Debug(args)
LoggerObj.Debug(args...)
}
Loading