Custom Format & Context

You can fully customize your logging output by adjusting the .format property of a destination. A simple but powerful variable-based syntax helps to achieve astonishing formatting, including JSON and color.

The character $ marks the start of "variable" followed by a case-sensitive letter.

Basic Example

let console = ConsoleDestination()
console.format = "$L: $M"  // loglevel: message
log.debug("Hello World")

// log output: 
DEBUG: Hello World

Setting the correct variables in .format gives you full customization. 

For example, you can adjust the date format by setting it between $D and $d using the standard Swift datetime format syntax. You can also colorize content of supported destinations by wrapping it with $C and $c. The used color depends on the log level.

More Examples, Including JSON

// log hour, minute and second, filename, function, line, log level & message
console.format = "$DHH:mm:ss$d $N.$F():$l $L: $M" 
// log output:
10:06:31 MyViewController.myFunction():123 DEBUG: a debug message

// log thread, date, time in milliseconds, level & message
console.format = "$Dyyyy-MM-dd HH:mm:ss.SSS$d $T $L: $M"
// log output:
2016-09-08 10:06:31.113 myThread DEBUG: My debug message

// log everything to a JSON string:
console.format = "$J"
// log output is JSON:
{"thread": "main", "file": "MyViewController.swift", "level": 1, "timestamp": 1487680870.503811,  "message": "Hello World", "function": "myFunction()", "line": 123}

Format Variables

Each variable represents a particular data from the logging event and starts with a $:

Variable Description
$L Level, for example "VERBOSE"
$M Message, for example the foo in log.debug("foo")
$J JSON-encoded logging object (can not be combined with other format variables!)
$N Name of file without suffix
$n Name of file with suffix
$F Function
$l Line (lower-case l)
$D Datetime, followed by standard Swift datetime syntax
$d Datetime format end
$T Thread
$C Color start, is just supported by certain destinations and is ignored if unsupported  
$c Color end
$U Uptime in the format HH:MM:SS
$X Optional context value of any type (see below)

Default Format

If you do not adjust your format then the following pattern will be used (including color where possible):

.format = "$DHH:mm:ss.SSS$d $C$L$c $N.$F:$l - $M"
// log output (DEBUG is in color):
2016-09-08 10:06:31.113 DEBUG MyViewController.myFunction():123 - My debug message


Optionally you can add context data to each log message of any type. On output it is added to the end of the log message:

.format = "$L: $M $X"   // show level, message and context value<br>// add context
log.debug("Message 1")
log.debug("Message 2", context: nil)
log.debug("Message 3", context: " yeah!")
log.debug("Message 4", context: 567)
log.debug("Message 5", context: [1, "a", 2])

// log output:
DEBUG: Message 1
DEBUG: Message 2
DEBUG: Message 3 yeah!
DEBUG: Message 4 567
DEBUG: Message 5 [1, \"a\", 2]

Still need help? Contact Us Contact Us