Logging in Swift

Ofcourse we can use print statements to output messages but this is pretty basic, a preference is for a logging framework which allows us to log different levels of information, for example debug, trace, info, error etc.

The documentation Generating Log Messages from Your Code shows that for macOS 11 and later to use the Logger structure. We can find a Logger implementation here apple swift-log.

We’ll need to update the Package.swift file in the Package dependencies as per the following

.package(url: "https://github.com/apple/swift-log.git", from: "1.0.0"),

Obviously change the version in the above to suit the latest available version.

Next, add the following to the (in my case) executableTarget

.product(name: "Logging", package: "swift-log")

To use the library in your code, declare a variable/const, for example

let logger: Logger = Logger(label: "com.putridparrot.EurekaService")

The label is output to the logger to distinguish the components which are logging.

Now to log we simply use

logger.info("Sending data")

The output would look like this

2022-03-05T16:39:52+0000 info com.putridparrot.EurekaService : Sending data

Out of the box the output is streamed to stderr, for example

LoggingSystem.bootstrap(StreamLogHandler.standardError)

Checkout the swift-log repository for more information on alternate LogHandlers.