swiftoslog

Using os_log to log function arguments, or other dynamic data


I'm trying to log function arguments into os_log like this:

func foo(x: String, y: [String:String]) {
    //...
    os_log("foo: \(x) \(y.description)", log: OSLog.default, type: .debug)
}

But getting error:

Cannot convert value of type 'String' to expected argument type 'StaticString'

So how can I log function arguments, or any other dynamic data?


Solution

  • Nowadays this question and the most popular answer are obsolete. Instead, use Logger, which supports string interpolation. The convenient way to use it is to define an instance of your logger globally in the app:

    extension Logger {
        static let myApp = Logger(subsystem: "com.mycompany", category: "MYAPP")
    }
    

    and then use it as

    Logger.myApp.debug("foo: \(x) \(y.description)")