26

There is a new logging system in iOS 10 and macOS Sierra.

But I can't seem to make it work in Xcode. os_log is not recognized, and neither is any other function / constant mentioned in the docs.

Use of unresolved identifier 'os_log'

Do I need to link a framework or import a header or something? Am I missing something obvious?

de.
  • 7,068
  • 3
  • 40
  • 69
Tom Hamming
  • 10,577
  • 11
  • 71
  • 145

2 Answers2

48

In Swift:

import os

os_log("Some message")

In Objective-C:

#import <os/log.h>

os_log(OS_LOG_DEFAULT, "Some message");
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • To those of you are annoyed by the requirement of adding a `import os.log` to any Swift file which you might ever want to drop a `os_log(...)` into, [here is some consolation](https://stackoverflow.com/questions/28694537/is-there-a-prefix-header-or-something-with-this-functionality-in-swift) – Jerry Krinock May 06 '19 at 17:42
  • To log with parameters you can use: `os_log(OS_LOG_DEFAULT, "Authorization Response: %@", URL);` – kyu Feb 17 '21 at 13:34
1

There are also bit advanced/organized way of logging, as mentioned at https://developer.apple.com/documentation/os/logging/generating_log_messages_from_your_code

In Swift,

let defaultLog = Logger()
defaultLog.log("This is a default message.")
            
// Log a message to the default log and debug log level
defaultLog.debug("This is a debug message.")

// Log an error to a custom log object.
let customLog = Logger(subsystem: "com.your_company.your_subsystem", 
          category: "your_category_name")
customLog.error("An error occurred!")

In Objective C

// Log a message to the default log and debug log level
os_log_with_type(OS_LOG_DEFAULT, OS_LOG_TYPE_DEBUG, "This is a debug message.");
    
// Log an error to a custom log object.
os_log_t customLog = os_log_create("com.your_company.your_subsystem", "your_category_name");
os_log_with_type(customLog, OS_LOG_TYPE_ERROR, "An error occurred!");
Trident
  • 810
  • 9
  • 20