Logrus.SetFormatter必须在SetOutput之前,因formatter在写入output前预处理日志entry;顺序颠倒会导致缓存按默认格式初始化、新formatter不生效,进而丢失时间/级别等字段。

Logrus 基础配置:为什么 logrus.SetFormatter 必须在 logrus.SetOutput 之前?
顺序错了会导致日志内容写入文件时格式错乱,甚至丢失时间、级别等字段。Logrus 的 formatter 是在写入 output 前对 entry 做预处理的,如果先设 output(比如指向一个 os.File),再设 formatter,部分内部缓存可能已按默认格式初始化,后续 formatter 不生效。
正确做法是固定三步顺序:
- 调用
logrus.New()或直接使用logrus包级 logger(注意并发安全) - 立即设置
logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true}) - 再设置
logrus.SetOutput(file),其中file是os.OpenFile打开的可写文件句柄
示例关键片段:
file, _ := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
logrus.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
DisableColors: true,
DisableSorting: true,
})
logrus.SetOutput(file)
JSON 格式输出到文件:为什么 logrus.JSONFormatter 的 TimestampFormat 默认不生效?
因为 logrus.JSONFormatter 默认把时间序列化为 Unix 时间戳(float64 秒),不是字符串。即使你设置了 TimestampFormat: "2006-01-02 15:04:05",它也只影响 TextFormatter;JSONFormatter 要显式启用字符串时间,必须设 DisableTimestamp: false 并配合 TimestampFormat —— 但实际有效的是 FieldMap 和底层 time.Time.MarshalJSON 行为。
立即学习“go语言免费学习笔记(深入)”;
更可靠的做法是:
- 用
logrus.JSONFormatter{TimestampFormat: "2006-01-02T15:04:05Z07:00"}(这个字段确实会被 JSONFormatter 读取) - 确保
logrus.SetLevel(logrus.InfoLevel)等级足够,否则 debug 日志不会输出 - 注意:JSON 输出里
time字段名由FieldMap控制,默认是time,不是timestamp
常见错误现象:"time":1712345678.123(Unix 时间戳)→ 改成上面带 TimestampFormat 的初始化即可变成字符串。
多文件轮转:Logrus 本身不支持,必须组合 lumberjack.Logger
Logrus 没有内置 rotate 功能。直接用 os.OpenFile 写死一个文件,跑几天后会撑爆磁盘。必须引入 gopkg.in/natefinch/lumberjack.v2。
关键点:
-
lumberjack.Logger实现了io.WriteCloser,可直接传给logrus.SetOutput - 注意
MaxSize单位是 MB(不是字节),MaxBackups是保留旧文件数,MaxAge是天数 - 不要在每次 log 之前重新 new lumberjack —— 它自己管理文件句柄和切换逻辑
典型配置:
logrus.SetOutput(&lumberjack.Logger{
Filename: "logs/app.log",
MaxSize: 50, // MB
MaxBackups: 7,
MaxAge: 28, // days
Compress: true,
})
结构化日志字段:为什么 WithFields 比拼接字符串更关键?
不用 logrus.WithFields,就只是普通文本日志,查问题时得靠正则硬扒。用了之后,每条日志是带 key-value 的结构体,方便 ELK、Loki 或 grep -o 提取。
实操建议:
- HTTP 请求日志推荐固定字段:
log.WithFields(logrus.Fields{"method": r.Method, "path": r.URL.Path, "status": status, "latency_ms": latency.Milliseconds()}) - 避免字段值含换行或控制字符,否则 JSON 格式会损坏;可提前用
strings.ReplaceAll(v, " ", "\n") - 全局 context 字段(如
request_id)适合用log.Entry.WithContext(ctx)+ 自定义 middleware 注入,而不是每个地方重复WithFields
容易被忽略的一点:Logrus 的 Entry 不是线程安全的,如果你把一个 log.WithFields(...) 得到的 Entry 在 goroutine 间传递并复用,字段可能被并发写乱 —— 应该在每个 goroutine 内部调用 WithFields。


















