Log to File

Logging to a file is great for development. You can tail your log file with the help of Terminal.app and on release you can attach the log file to an email or send it to your server. The file location is adjustable and on default the file is stored in the Document directory of your app.

SwiftyBeaver Framework automatically adds color to each log message without the need for 3rd party plugins. 

Screenshot of Terminal.app while tailing a log file

Setup

To start logging to a file you just need to instantiate  FileDestination(), optionally adjust the properties and then add the instance to SwiftyBeaver itself. Logging in a different format to multiple files is possible if several file destination instances are created and added (example see further down below). A non-existing file is automatically created.

let file = FileDestination()
log.addDestination(file)

Properties

You can adjust the logging behavior with the following properties of FileDestination().

Property Default Description
.logFileURL Caches Directory +
"swiftybeaver.log"
The default filename is  swiftybeaver.log and it is stored in the app’s Caches Directory. During development it is recommended to change that logfileURL to /tmp/swiftybeaver.log so that the file can be tailed by a Terminal app using the CLI command tail -f /tmp/swiftybeaver.log
.format
Customize the   log format output, on default it shows every detail with a colored log level
.asynchronously true Runs on own serial background thread for better performance. Set to   false during development for easier debugging.
.minLevel .verbose Any level with a priority lower than that level is not logged. Possible values are SwiftyBeaver.Level.verbose, .debug, .info .warning, .error. 
.levelString.verbose, .debug, .info, .warning, .error "VERBOSE", "DEBUG", etc. Sets a custom string representing the log level. On default it is the log level as uppercase word.

Example with logging to 2 files in parallel:

let file = FileDestination() // get new file destination instance
// uses standard logging to swiftybeaver.log in the application cache directory
console.format = "$DHH:mm:ss$d $C$L$c: $M"  // hour, minute, second, colored log level and message
file.minLevel = Level.verbose
log.addDestination(file) // add to SwiftyBeaver to use destination

// the second file with different properties and custom filename
let file2 = FileDestination()
file2.format = "$Dyyyy-MM-dd HH:mm:ss.SSS$d $C$L$c: $M"  // full datetime, colored log level and message
file2.minLevel = Level.info
file2.levelString.error = "Beaver Love!"
file2.logFileURL = URL(fileURLWithPath: "/tmp/app_info.log")  // tmp is just possible for a macOS app
log.addDestination(file2)

Still need help? Contact Us Contact Us