2024-09-01 00:06:18 +08:00
|
|
|
# logx
|
2024-09-01 00:03:12 +08:00
|
|
|
|
2024-09-01 00:06:18 +08:00
|
|
|
logx 是一个灵活、高效的 Go 日志库,基于 Go 1.21 引入的 `log/slog` 包构建。它提供了结构化日志记录、多处理程序支持、上下文感知和全局日志记录器等功能。
|
2024-09-01 00:03:12 +08:00
|
|
|
|
|
|
|
## 安装
|
|
|
|
|
|
|
|
```bash
|
|
|
|
go get -u github.com/yeqown/logx
|
|
|
|
```
|
|
|
|
|
2024-09-01 00:06:18 +08:00
|
|
|
## 快速开始
|
2024-09-01 00:03:12 +08:00
|
|
|
|
|
|
|
```go
|
2024-09-01 00:06:18 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"log/slog"
|
|
|
|
|
|
|
|
"gitea.cccvno1.com/chenchi/logx"
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
logger := logx.New(
|
|
|
|
logx.WithConsoleHandler(slog.LevelDebug),
|
|
|
|
logx.WithFileHandler("app.log", 10, 5, 30, true, slog.LevelInfo),
|
|
|
|
)
|
|
|
|
|
|
|
|
logx.SetGlobalLogger(logger)
|
|
|
|
|
|
|
|
logx.Info("Application started")
|
|
|
|
|
|
|
|
ctx := context.WithValue(context.Background(), "trace_id", "abc123")
|
|
|
|
contextLogger := logx.WithContext(ctx)
|
|
|
|
contextLogger.Debug("This is a debug message with context")
|
|
|
|
|
|
|
|
// 使用结构化日志
|
|
|
|
logx.Info("User logged in",
|
|
|
|
slog.String("username", "john_doe"),
|
|
|
|
slog.Int("user_id", 12345),
|
|
|
|
)
|
|
|
|
|
|
|
|
logger.Close()
|
|
|
|
}
|
|
|
|
```
|