8.2 KiB
logx 类型与方法说明
- LogConf LogConf 是日志配置结构体,用于设置日志相关的各项参数。
type LogConf struct {
ServiceName string json:",optional"
Mode string json:",default=console,options=[console,file,volume]"
Encoding string json:",default=json,options=[json,plain]"
TimeFormat string json:",optional"
Path string json:",default=logs"
Level string json:",default=info,options=[debug,info,error,severe]"
MaxContentLength uint32 json:",optional"
Compress bool json:",optional"
Stat bool json:",default=true"
KeepDays int json:",optional"
StackCooldownMillis int json:",default=100"
MaxBackups int json:",default=0"
MaxSize int json:",default=0"
Rotation string json:",default=daily,options=[daily,size]"
} 2. WithColor
在纯文本编码时,给字符串添加颜色。
func WithColor(text string, colour color.Color) string 参数:
text: 要添加颜色的文本。 colour: 颜色对象。 返回值: 返回带颜色的字符串。
示例代码 import "github.com/fatih/color"
text := "Hello, World!" coloredText := logx.WithColor(text, color.FgRed) fmt.Println(coloredText) 3. AddGlobalFields 添加全局字段,这些字段将被添加到所有日志条目中。
func AddGlobalFields(fields ...LogField) 参数: fields: 要添加的全局字段。 示例代码 logx.AddGlobalFields(logx.Field("service", "my-service")) 4. ContextWithFields 返回包含给定字段的上下文。
func ContextWithFields(ctx context.Context, fields ...LogField) context.Context 参数:
ctx: 上下文对象。 fields: 要添加到上下文中的字段。 返回值: 返回新的上下文对象。
示例代码 ctx := context.Background() ctx = logx.ContextWithFields(ctx, logx.Field("request_id", "12345")) 5. Logger 接口 Logger 接口定义了日志记录的方法。
type Logger interface { Debug(...any) Debugf(string, ...any) Debugv(any) Debugw(string, ...LogField) Error(...any) Errorf(string, ...any) Errorv(any) Errorw(string, ...LogField) Info(...any) Infof(string, ...any) Infov(any) Infow(string, ...LogField) Slow(...any) Slowf(string, ...any) Slowv(any) Sloww(string, ...LogField) WithCallerSkip(skip int) Logger WithContext(ctx context.Context) Logger WithDuration(d time.Duration) Logger WithFields(fields ...LogField) Logger } 示例代码 var logger logx.Logger = logx.WithContext(context.Background())
logger.Info("This is an info log") logger.Debugf("Debug log with value: %d", 42) logger.Errorw("Error occurred", logx.Field("error_code", 500)) 6. NewLessLogger 创建一个间隔一定时间内只记录一次日志的 LessLogger。
func NewLessLogger(milliseconds int) *LessLogger 参数:
milliseconds: 时间间隔(毫秒)。 返回值: 返回 LessLogger 对象。
示例代码 lessLogger := logx.NewLessLogger(1000)
lessLogger.Error("This error will be logged at most once per second") 7. NewWriter 创建一个新的 Writer 实例。
func NewWriter(w io.Writer) Writer 参数:
w: 一个实现了 io.Writer 接口的实例。 返回值: 返回 Writer 接口的实现。
示例代码 file, err := os.Create("app.log") if err != nil { log.Fatal(err) } writer := logx.NewWriter(file) logx.SetWriter(writer) 日志配置示例 logConf := logx.LogConf{ ServiceName: "example-service", Mode: "file", Encoding: "json", Path: "/var/logs", Level: "debug", KeepDays: 7, MaxContentLength: 1024, Compress: true, }
err := logx.SetUp(logConf) if err != nil { log.Fatalf("Failed to set up logging: %v", err) }
logc logc 包封装了 go-zero 中 logx 包的日志功能,提供了一些便捷的方法来记录不同级别的日志。
类型定义 type ( LogConf = logx.LogConf LogField = logx.LogField ) 函数列表 AddGlobalFields 添加全局字段,这些字段会出现在所有的日志中。
func AddGlobalFields(fields ...LogField) 示例:
logc.AddGlobalFields(logc.Field("app", "exampleApp")) Alert 以警告级别记录日志信息,该信息会写入错误日志。
func Alert(_ context.Context, v string) 示例:
logc.Alert(context.Background(), "This is an alert message") Close 关闭日志记录系统。
func Close() error 示例:
if err := logc.Close(); err != nil { fmt.Println("Error closing log system:", err) } Debug 记录调试级别的日志信息。
func Debug(ctx context.Context, v ...interface{}) 示例:
logc.Debug(context.Background(), "This is a debug message") Debugf 格式化记录调试级别的日志信息。
func Debugf(ctx context.Context, format string, v ...interface{}) 示例:
logc.Debugf(context.Background(), "This is a %s message", "formatted debug") Debugv 以 JSON 格式记录调试级别的日志信息。
func Debugv(ctx context.Context, v interface{}) 示例:
logc.Debugv(context.Background(), map[string]interface{}{"key": "value"}) Debugw 记录带字段的调试级别的日志信息。
func Debugw(ctx context.Context, msg string, fields ...LogField) 示例:
logc.Debugw(context.Background(), "Debug message with fields", logc.Field("key", "value")) Error 记录错误级别的日志信息。
func Error(ctx context.Context, v ...any) 示例:
logc.Error(context.Background(), "This is an error message") Errorf 格式化记录错误级别的日志信息。
func Errorf(ctx context.Context, format string, v ...any) 示例:
logc.Errorf(context.Background(), "This is a %s message", "formatted error") Errorv 以 JSON 格式记录错误级别的日志信息。
func Errorv(ctx context.Context, v any) 示例:
logc.Errorv(context.Background(), map[string]interface{}{"error": "something went wrong"}) Errorw 记录带字段的错误级别的日志信息。
func Errorw(ctx context.Context, msg string, fields ...LogField) 示例:
logc.Errorw(context.Background(), "Error message with fields", logc.Field("key", "value")) Field 返回一个日志字段。
func Field(key string, value any) LogField 示例:
field := logc.Field("key", "value") Info 记录信息级别的日志信息。
func Info(ctx context.Context, v ...any) 示例:
logc.Info(context.Background(), "This is an info message") Infof 格式化记录信息级别的日志信息。
func Infof(ctx context.Context, format string, v ...any) 示例:
logc.Infof(context.Background(), "This is a %s message", "formatted info") Infov 以 JSON 格式记录信息级别的日志信息。
func Infov(ctx context.Context, v any) 示例:
logc.Infov(context.Background(), map[string]interface{}{"info": "some information"}) Infow 记录带字段的信息级别的日志信息。
func Infow(ctx context.Context, msg string, fields ...LogField) 示例:
logc.Infow(context.Background(), "Info message with fields", logc.Field("key", "value")) Must 检查错误,如果发生错误则记录错误并退出程序。
func Must(err error) 示例:
logc.Must(errors.New("fatal error")) MustSetup 根据给定的配置初始化日志系统,如有错误则退出程序。
func MustSetup(c logx.LogConf) 示例:
config := logx.LogConf{ ServiceName: "exampleService", Mode: "console", } logc.MustSetup(config) SetLevel 设置日志级别,可以用来抑制某些日志。
func SetLevel(level uint32) 示例:
logc.SetLevel(logx.LevelInfo) SetUp 根据给定的配置初始化日志系统。如果已经初始化,将不再重复初始化。
func SetUp(c LogConf) error 示例:
config := logc.LogConf{ ServiceName: "exampleService", Mode: "console", } if err := logc.SetUp(config); err != nil { fmt.Println("Error setting up log system:", err) } Slow 记录慢日志。
func Slow(ctx context.Context, v ...any) 示例:
logc.Slow(context.Background(), "This is a slow log message") Slowf 格式化记录慢日志。
func Slowf(ctx context.Context, format string, v ...any) 示例:
logc.Slowf(context.Background(), "This is a %s message", "formatted slow log") Slowv 以 JSON 格式记录慢日志。
func Slowv(ctx context.Context, v any) 示例:
logc.Slowv(context.Background(), map[string]interface{}{"slow": "operation details"}) Sloww 记录带字段的慢日志。
func Sloww(ctx context.Context, msg string, fields ...LogField) 示例:
logc.Sloww(context.Background(), "Slow log message with fields", logc.Field("key", "value"))