# xlog **Repository Path**: xgo-core/xlog ## Basic Information - **Project Name**: xlog - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-06-14 - **Last Updated**: 2026-07-04 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # xlog `xlog` 是一个基于 Logrus 的 XGo 日志包。它通过 `LogConf` 创建包级 logger,并通过配置的 hook 输出日志。 ## 功能 - 支持 Logrus level 和 fields。 - 支持从 XGo context 提取 trace ID。 - 支持 stdout 和 file hook。 - 支持 text 和 JSON 输出格式。 - 支持可选 caller 输出。 - 支持按时间滚动文件。 - 内部 Logrus 输出使用 discard formatter,避免 hook 已经格式化后再做一次默认格式化。 ## 安装 ```bash go get gitee.com/xgo-core/xlog ``` ## 配置 如需覆盖默认配置,需要在第一次写日志前向 XGo container 注入一个配置实例: ```go container.MustInject(&xlog.LogConf{ Level: xlog.InfoLevel, Options: xlog.Options{ ReportCaller: true, }, Hooks: []xlog.Hook{ xlog.HookStdout, xlog.HookFile, }, Clients: xlog.Clients{ Stdout: xlog.StdoutClient{ Format: xlog.FormatText, Colorful: true, }, File: xlog.FileClient{ File: "logs/app.log", Format: xlog.FormatJSON, Rotation: xlog.Rotation{ Enable: true, Interval: xlog.RotationDay, MaxFile: 30, }, }, }, }) ``` `xlog` 通过 `container.GetAs[xlog.ConfigInterface]()` 读取配置。请只注入一个可赋值给 `xlog.ConfigInterface` 的配置实例;否则最新的 container 包会返回多实例错误。 JSON 配置结构: ```json { "level": 4, "options": { "ReportCaller": true }, "hooks": ["stdout", "file"], "clients": { "stdout": { "format": "text", "colorful": true }, "file": { "file": "logs/app.log", "format": "json", "colorful": false, "rotation": { "enable": true, "interval": "day", "max_file": 30 } } } } ``` `level` 使用 `xlog.Level` 的数字值。常用值:`5` debug,`4` info,`3` warn,`2` error,`6` trace。 ## 使用 ```go ctx := context.New() xlog.WithContext(ctx). WithFields(map[string]any{ "module": "billing", "user": 1001, }). Info("invoice created") xlog.WithField("module", "billing").Warn("retrying payment") ``` 启用文件日志时,进程退出前调用 `Close`: ```go defer xlog.Close() ``` ## 输出格式 text 输出包含固定字段: ```text 2026-06-16 17:30:45.123 | INFO | invoice created | trace-id | {"module":"billing"} | /path/file.go:42 ``` JSON 输出包含: ```json { "datetime": "2026-06-16 17:30:45.123", "level": "INFO", "message": "invoice created", "trace": "trace-id", "fields": { "module": "billing" }, "caller": "/path/file.go:42" } ``` ## 文件滚动 支持的滚动周期: - `xlog.RotationHour` - `xlog.RotationDay` - `xlog.RotationMonth` 开启滚动后,日志文件名会根据配置文件名追加时间后缀,例如 `logs/app.20260616.log`。 ## 测试 ```bash go test ./... ```