Using os_log to log function arguments, or other dynamic data

前端 未结 5 1526
一向
一向 2021-01-03 00:24

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

func foo(x: String, y: [String:String]) {
    //...
    os_log(\"foo: \\(x) \\(y.de         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-03 00:47

    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.

提交回复
热议问题