What is os.log for?

TonyStark4ever picture TonyStark4ever · Jun 1, 2017 · Viewed 8.9k times · Source

I am going through a few Swift tutorials on how to build simple apps, as I am just starting to code. I want to make my app iOS 9 compatible, as I have an iPad 3. However, all the os.log statements generate an error in Xcode which tells me to add an if #avaliable statement before any of the os.log statements. What does os.log do, and if I need it, is there an issue using an if #avaliable statement for iOS 9 compatibility? If not, what is the equivalent code for iOS 9 to go in the else statement after the if #avaliable statement? Thanks.

Answer

David S. picture David S. · Jun 1, 2017

From Apple's documentation:

Unified logging is available in iOS 10.0 and later, macOS 10.12 and later, tvOS 10.0 and later, and watchOS 3.0 and later, and supersedes ASL (Apple System Logger) and the Syslog APIs. Historically, log messages were written to specific locations on disk, such as /etc/system.log. The unified logging system stores messages in memory and in a data store, rather than writing to text-based log files.

There is no iOS9 equivalent. You could use a third party logging tool like CocoaLumberjack, which is very popular.

As a concrete example of how to use this logging:

if #available(iOS 10.0, *) {
    let bundleID:String = Bundle.main.bundleIdentifier ?? "unknown"
    let oslog = OSLog(subsystem: bundleID, category: "Model")
    os_log("%@", log: oslog, type: .info, message)
}