How do you pass an Error to os_log from Swift?

I am trying to log an error from a catch block. The documentations says the following:

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

In addition to standard format string specifiers, such as %@ and %d, the logging system supports custom decoding of values by denoting value types inline in the format %{value_type}d. In addition, the specifier %.*P can be used to decode arbitrary binary data. The system includes a number of built-in value type decoders, shown in Table 3.

errno %{errno}d Broken pipe

When I do this I get an error:

import os.log

do {
    try throwError()
} catch {
    os_log("Error: %{errno}d", log: .default, type: .error, error)

However the compiler outputs errors with:

Argument type 'Error' does not conform to expected type 'CVarArg'

Is there a better way than passing error.localizedDescription as the argument?

1 answer

  • answered 2020-01-17 18:08 Joakim Danielson

    Use @ instead of d and convert the error into a String

    os_log("Error: %@", log: .default, type: .error, String(describing: error))