go - 如何向 ZAP 日志条目添加新列/字段?
问题描述
我有以下日志结构:
[STDERR] 2018-07-09 11:06:16.003 INFO some_pkg/main.go:232 Logging message 1 {"pid": 8842, "process": "some_process"}
[STDERR] 2018-07-09 11:06:16.006 DEBUG some_pkg/main.go:291 Logging message 2 {"pid": 8842, "process": "other_process"}
[STDERR] 2018-07-09 11:06:16.009 INFO some_pkg/main.go:345 Logging message 3 {"pid": 8842, "process": "some_process"}
您可以在此日志记录片段中看到五种类型的信息。有日期/时间、日志级别、发生、消息和 JSON 字段([STDERR] 字段除外)。这意味着我的日志结构中有五列。我想添加一个带有关键pid和进程(来自 JSON)的新列。我应该如何使用 ZAP 编码器和配置来做到这一点?我在 ZAP 文档中没有找到解决方案。
我使用以下代码将字段添加到日志记录:
logger = logger.With(zap.Field{Key: "pid", Type: zapcore.Int64Type, Integer: int64(os.Getpid())})
但是 pid 字段的值转到 JSON(您可以在上面看到),我想在新列中看到它。ZAP 中有一种简单的方法可以做到这一点吗?
在前面的示例中,我想要的结构如下:
[STDERR] 2018-07-09 11:06:16.003 INFO some_pkg/main.go:232 Logging message 1 8842 some_process
[STDERR] 2018-07-09 11:06:16.006 DEBUG some_pkg/main.go:291 Logging message 2 8836 other_process
[STDERR] 2018-07-09 11:06:16.009 INFO some_pkg/main.go:345 Logging message 3 8842 some_process
解决方案
The requested logging style would result in a mix of structured logging (json) and unstructured logging (all other fields in console).
blackgreen's answer should make it possible and its a good hack, but the bigger problem here I think is that you are working against what zap has to offer (Blazing fast, structured, leveled logging in Go.).
Recommended approach would be put everything in json and parse json keys in whatever log viewer you are using. Resuling log structure looks something like:
{"timeStamp": "2018-07-09 11:06:16.003", "level": "INFO", "source": "some_pkg/main.go:232", "msg": "Logging message 1", "pid": 8842, "process": "some_process"}
推荐阅读
- python - 如何为 LSTM 和 Keras 构建面板数据?
- python - 加快 for 循环下的嵌套 if 循环
- javascript - 删除动画子节点的动画迭代事件侦听器
- javascript - Axios 未在 Vuex 商店中正确设置 - Vue.js 和 Electron
- mysql - 一列是多个复合 FK 约束的一部分,是否有效且良好的设计决策?
- db2 - 如何计算数据为十进制时的时间差异?
- sql - SQL JOIN 将多个项目返回到 1 行
- debugging - 当消息不被理解时,Pharo 如何启动调试器?
- c# - JWT Bearer Authentication 不从标头中读取 Token
- c - 插入排序错误