首页 > 解决方案 > 如何向 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

标签: gologginggo-zap

解决方案


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"}

推荐阅读