2

I'm wondering how I'm supposed to handle the following fairly common scenario using Unified Logging. Let's say I have an object of class Foo which I want to log. Foo implements the CustomStringConvertible protocol, so I can get a description of the object I can use in my logs:

class Foo: CustomStringConvertible {
     var bar:Int = 1

     var description: String {
          return "<\(type(of: self)): bar = \(bar)>"
     }
}

let myFoo = Foo()

If I call print(myFoo), I get a nice description of Foo. However, os_log(myFoo) won't work since description is not a StaticString. Is there a way to accomplish what I'm trying to do?

pondermatic
  • 6,453
  • 10
  • 48
  • 63

1 Answers1

4

A string doesn't have to be static, as long as the format includes %{public}@. Here's a complete example:

import UIKit
import os
let mylog = OSLog(subsystem: "com.neuburg.matt", category: "testing")
class Foo: CustomStringConvertible {
    var bar:Int = 1
    var description: String {
        return "<\(type(of: self)): bar = \(bar)>"
    }
}
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let foo = Foo()
        os_log("%{public}@", log: mylog, String(describing:foo))
    }
}

Prints:

[testing] <Foo: bar = 1>

...which I believe was the goal.

matt
  • 515,959
  • 87
  • 875
  • 1,141