apple / swift-log

A Logging API for Swift
https://apple.github.io/swift-log/
Apache License 2.0
3.48k stars 284 forks source link

Support advanced loghandler metadata use cases #270

Closed Mordil closed 6 months ago

Mordil commented 1 year ago

Description

Different logging backends support different "levels of metadata", allowing users to specify essentially indexed metadata vs. standard "extra metadata".

For example, Sentry allows users to attach data explicitly to their events as tags, while everything else is attached as "extra context".

Tags will be indexed and queryable, while "extra" are only available to view from Sentry incident reports.

However, there's no way to forward this information down to individual logs.

Concrete ask

I think there's an easy path here to support this in a backwards compatible way, as an opt-in for LogHandler conformers to implement.

Essentially, we just provide an implementation-specific prefix on metadata keys labeled as tags that can be parsed before being sent to a backend.

This way, if a log handler doesn't support it, the only negative downside is potentially "unexpected" keys, but this requires the developer to have explicitly called this API

For example

extension Logger {
  /// Accesses and stores the metadata value to be used as a tag, if supported by log handlers.
  public subscript(tagKey tagKey: String) -> Metadata.Value? {
    get {
      return self[metadataKey: "tag_\(tagKey)]
    }
    set(newValue) {
      self[metadataKey: "tag_\(tagKey)"] = newValue
    }
  }
}
ktoso commented 1 year ago

Hm, but you can write this extension yourself and other libraries don't know about this convention so how would they use the "tag key" -- they dont know about it, and most backends don't respect this so it is weird to expect library authors to know and respect tag/metadata difference if they never benefit from it -- so it's more for your application code and libs, in which case -- do the extension?

Why does this have to be done in swift-log?

Mordil commented 1 year ago

That's a fair argument.

We have this code locally, but it's non-trivial to get right. (I've had to fix simple mistakes twice now, with oodles of tests)

I think my reflex was that of the stereotypical "this is useful sharable code, let's put it in the library!" response.

Perhaps we want a SwiftLogExtras type of module like we've done for other libraries, where this might be able to live.