Another Look at Swift Logging

Swift 3.0 ISC

Shortly after Apple released Swift a number of folks provided logging libraries, as the venerable Lumberjack didn’t work out of the box. We even provided a little write-up on using swiftlog, a collection of simple logging routines.

Well, we’re back with an update to swiftlog that focuses on providing a quick way to add log messages to Swift applications on Linux systems. The new features include:

  • SwiftPM-ready
  • color-coded log messages using the awesome Rainbow package
  • ability to write log messages to a file

As with all incarnations of swiftlog, we are not looking to develop the Cadillac of logging frameworks. swiftlog is a very simple and no frills package.

Using swiftlog

To use the new swiftlog just add it to your Package.swift dependencies:

You can begin using the logging facility by importing swiftlog and setting the sLogLevel global variable (it defaults to .None which turns logging off).

All logs equal to or higher in severity are printed. Logs are color-coded as well:

Colored Logs!
Colored Logs!

It doesn’t take a rocket surgeon to determine the options available for sLogLevel, but for completeness here they are:

  • .None
  • .Verbose
  • .Info
  • .Warning
  • .Error

Two additional routines are provided: ENTRY_LOG and EXIT_LOG. These “macros” are designed for tracing function entry and exits in your logs:

This results in three additional log messages:

VERBOSE - ENTRY multiply(_:multiplier:)
VERBOSE - EXIT  multiply(_:multiplier:)
VERBOSE - 10 times 10 equals 100

Finally, we can instruct that logs also be written to a file with slogToFile(atPath:).

The append parameter of slogToFile(atPath:) can be set to false to overwrite the previous contents of the file.

The Code

You can grab the code on Github. If you don’t like the colors I chose for the log levels, hack away! Perhaps a new revision will provide for more customization and options; I’ve deliberately chosen thus far to make this package very simple to use and reduced the number of knobs.

There is an example in the logexample directory of the repository. Enter logexample and type swift build to build and run!

Leave a Reply

Your email address will not be published. Required fields are marked *