How can I construct custom loggers?

I'm looking to construct a custom logger API. For example:

log.verbose(Date(), "Begun process")

(That's contrived example, the point being some object and a message. I will then be manipulating both.)

Within my Log object I then want to transform the date value and the message into a final log message. "Nanoseconds: 9790324:: Begun process". If I was working with strings, it would be a pretty simple issue. But I'm not. It looks like Logger, which actually does the logging takes in a OSLogMessage which I cannot instantiate and cannot pass by value or reference. Even if I had just:

func verbose(_ date: Date, _ message: OSLogInterpolation) {
  log(date: Date, level: .info, message: message)
}

func info(_ date: Date, _ message: OSLogInterpolation) {
  log(date: Date, level: .default, message: message)
}

private func log(date: Date, level: OSLogType, message: OSLogInterpolation) {
 // Neither of these work
  log.log(level: level, message)
  log.log(level: level, OSLogMessage(interpolation: message))
}

Ideally what I'd like is:

private func log(date: Date, level: OSLogType, message: OSLogInterpolation) {
  let interpolation = "Nanoseconds: \(date.getNanoseconds):: " + message
  log.log(level: level, OSLogMessage(interpolation: interpolation))
}

With the idea being that OSLogMessage is still respecting any privacy notices on the interpolation.

Replies

I’m confused by your goals here. The system log already includes high-resolution timestamps in all log entries. Why do you want to add an additional one?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

  • It's less about the system logs. I'm interested in building out an analytics package for tracking the efficiency of my app. The data will be transmitted to the server and it will be useful to include messages. My preference would be to use OSLog's token privacy system to ensure that private data stays private. That was the initial idea.

    Even after that, the idea that I could construct my own logging API that would take custom objects and then support rendering a message with some interpolated string is something that I'd like to be able to do from the standpoint as a framework author. Consider:

    struct HealthRecord { let name: String let criticalHealthRecord: HIPAA let nonIdentifyingInformation: Int }

    Being a developer who both who both wants to provide a valuable logging experience and protect users privacy. My method will provide privacy compliance and amend the client's OSLogMessage in a single log statement by calling log(_ record: HealthRecord, _ message: OSLogInterpolation).

Add a Comment

The Logger type is seriously intertwined with the compiler and, as such, is not suitable for this purpose.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"