StackdriverLogging

一个 SwiftLog LogHandler,用于记录 GCP Stackdriver 格式的 JSON。

有关 Stackdriver 结构化日志记录的更多信息,请参阅:https://cloud.google.com/logging/docs/structured-loggingLogEntry

依赖项

此 Stackdriver LogHandler 依赖于 SwiftNIO,它用于以非阻塞方式创建和保存您的新日志条目。

如何安装

Swift Package Manager

.package(url: "https://github.com/Brainfinance/StackdriverLogging.git", from: "4.0.0"),

在您的目标依赖项中添加 "StackdriverLogging",例如这样

.target(name: "App", dependencies: ["StackdriverLogging"]),

Vapor 4

这是一个标准 Vapor 4 应用程序的引导示例。

import App
import Vapor

var env = try Environment.detect()
try LoggingSystem.bootstrap(from: &env) { (logLevel) -> (String) -> LogHandler in
    return { label -> LogHandler in
        var logger = StackdriverLogHandler(destination: .stdout)
        logger.logLevel = logLevel
        return logger
    }
}
let app = Application(env)
defer { app.shutdown() }
try configure(app)
try app.run()

使用 Logger.MetadataValue 记录 JSON 值

要将元数据值记录为 JSON,只需将所有 JSON 值(String 除外)记录为 Logger.MetadataValue.stringConvertible,并且在日志条目中,它将保持值的原始 JSON 类型,而不是像通常那样将值转换为 String(如果可能)。

例如

var logger = Logger(label: "Stackdriver")
logger[metadataKey: "jsonpayload-example-object"] = [
    "json-null": .stringConvertible(NSNull()),
    "json-bool": .stringConvertible(true),
    "json-integer": .stringConvertible(1),
    "json-float": .stringConvertible(1.5),
    "json-string": .string("Example"),
    "stackdriver-timestamp": .stringConvertible(Date()),
    "json-array-of-numbers": [.stringConvertible(1), .stringConvertible(5.8)],
    "json-object": [
        "key": "value"
    ]
]
logger.info("test")

将记录未经美化的以下表示形式

{  
   "sourceLocation":{  
      "function":"boot(_:)",
      "file":"\/Sources\/App\/boot.swift",
      "line":25
   },
   "jsonpayload-example-object":{  
      "json-bool":true,
      "json-float":1.5,
      "json-string":"Example",
      "json-object":{  
         "key":"value"
      },
      "json-null":null,
      "json-integer":1,
      "json-array-of-numbers":[  
         1,
         5.8
      ],
      "stackdriver-timestamp":"2019-07-15T21:21:02.451Z"
   },
   "message":"test",
   "severity":"INFO"
}

从托管平台记录

如果您的应用在托管环境中运行,例如 Google Cloud Run 或基于容器的 Compute Engine,则记录到 stdout 应该可以让您自动启动并运行。

Stackdriver 日志代理 + fluentd 配置

如果您更喜欢记录到文件,您可以将文件目标 StackdriverLogHandler.Destination.file 与 Stackdriver 日志代理 https://cloud.google.com/logging/docs/agent/installation 和匹配的 json 格式 google-fluentd 配置 (/etc/google-fluentd/config.d/example.conf) 结合使用,以自动将您的 JSON 日志发送到 Stackdriver。

这是一个示例 google-fluentd 配置文件,它监视基于 json 的日志文件并将新的日志条目发送到 Stackdriver

<source>
    @type tail
    # Format 'JSON' indicates the log is structured (JSON).
    format json
    # The path of the log file.
    path /var/log/example.log
    # The path of the position file that records where in the log file
    # we have processed already. This is useful when the agent
    # restarts.
    pos_file /var/lib/google-fluentd/pos/example-log.pos
    read_from_head true
    # The log tag for this log input.
    tag exampletag
</source>