Using os_log to log function arguments, or other dynamic data

早过忘川 提交于 2019-12-04 02:13:30

问题


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?


回答1:


See Logging:

Formatting Log Messages

To format a log message, use a standard NSString or printf format string, ...

and String Format Specifiers for the standard format string specifiers, such as %@ and %d.

In your case:

os_log("foo: %@ %@", log: .default, type: .debug, x, y.description)

The format string is restricted to static strings to prevent (unintentional) expansion of format string specifiers. Here is an example demonstrating the problem, using NSLog() because that does not restrict the format to constant strings:

let s = "50%"
NSLog("\(s)percent")
// Output: 500x0ercent

The %p expects a pointer on the variable argument list, which is not provided. This is undefined behavior, it can lead to crashes or unexpected output.



来源:https://stackoverflow.com/questions/53025698/using-os-log-to-log-function-arguments-or-other-dynamic-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!