Golang中如何使用Logrus动态添加嵌套日志字段?
实现方案
logrus 中的 logrus.Fields 本质是 map[string]interface{} 类型,你需要的嵌套 details 字段本身也是一个 Fields 结构,只需要每次操作时取出已有的嵌套 map、追加新字段后重新覆盖回顶层字段即可实现动态添加:
基础实现示例
package main import "github.com/sirupsen/logrus" func main() { // 初始化日志实例与基础字段 logger := logrus.New() baseFields := logrus.Fields{ "details": logrus.Fields{ "app_name": "Some name", "app_version": "Some version", }, } // 注意 WithFields 会返回新的 Entry 实例,必须接住返回值 currentLog := logger.WithFields(baseFields) // 执行步骤1,追加对应字段 details := currentLog.Data["details"].(logrus.Fields) details["step1_status"] = "success" details["step1_cost"] = "12ms" currentLog = currentLog.WithField("details", details) // 执行步骤2,继续追加字段 details = currentLog.Data["details"].(logrus.Fields) details["step2_status"] = "fail" details["step2_err_msg"] = "invalid user id" currentLog = currentLog.WithField("details", details) // 最终输出会包含所有嵌套在 details 下的累积字段 currentLog.Error("API 处理结束") }
注意事项
- 类型断言可以增加安全校验,避免运行时 panic:
details, ok := currentLog.Data["details"].(logrus.Fields) if !ok { // 如果不存在 details 字段则初始化 details = logrus.Fields{} } - 如果需要频繁操作嵌套字段,可以封装为通用工具方法简化调用:
func AppendDetail(logEntry *logrus.Entry, key string, value interface{}) *logrus.Entry { details, ok := logEntry.Data["details"].(logrus.Fields) if !ok { details = logrus.Fields{} } details[key] = value return logEntry.WithField("details", details) } // 调用示例 currentLog = AppendDetail(currentLog, "user_id", 10086) currentLog = AppendDetail(currentLog, "step3_status", "success")
内容的提问来源于stack exchange,提问作者Lee Maan
相关产品推荐
相关产品推荐

