Logging in Swift

Here is my poor man version of logging for SWIFT

func logPrint(logMessage: Any, _ file: String = __FILE__, _ function: String = __FUNCTION__, line: Int = __LINE__) {
    print("\(file):\(line):0: \(function): \(logMessage)")
}

This method besides printing your message it shows the file name, the line and the function method where the log was made. The file, function and line numbers are extracted using literal expressions.

This makes it easier to find where the log message come from and if you have the KZLinkedConsole plugin installed in Xcode you just need to click on the error message in the console and Xcode will take you there.

For a more advanced logging library I recommend XCGLogger

== Update (2016-01-25) ==

I found out that the print statement doesn’t print to the System Logs, this could be useful in scenarios that you want to see the log message on a user device. So I update my method to use the NSLog function

func logPrint(logMessage: Any, _ file: String = __FILE__, _ function: String = __FUNCTION__, line: Int = __LINE__) {
    NSLog("\(file):\(line):0: \(function): \(logMessage)")
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close