Logging for learners in Swift


Learn to print variables to the debug console utilizing totally different capabilities reminiscent of print, dump, NSLog and the unified os.log API.

Swift

Primary output in Swift utilizing print

The very first technique I would like to point out you is the print operate. It may write the textual illustration of the given objects to the usual output. In different phrases we will merely say that it could possibly print textual content to the display. Many of the hi there phrase applications make the most of this technique to show the well-known “Good day world!” message. In Swift, print is sort of a robust technique, since you may go round a number of objects for printing out plus you may specify a separator string and a terminator parameter. πŸ€”

print("Good day World!")

The snippet above will show the Good day World! textual content adopted by a newline character (n), it is because the default terminator is at all times a newline. You possibly can override this habits by offering your individual terminator string.

print("Good day World!", terminator: "")

In case you run this instance utilizing Xcode you must see that the “Program ended with exit code: 0” textual content will seem in a newline within the first case, however within the second situation it’s going to be printed out proper after the “Good day World!” sentence. In case you run this system utilizing a Terminal software, a % character be current as a substitute of the brand new line within the second case. πŸ’‘

What about printing out a number of variables? It’s potential to present a number of objects to the print operate, they are often actually something, print can deal with strings, integers and all types of different variables. Print below the hood will convert the variable into a correct string illustration, so you do not have to fiddle with sort casting on a regular basis, however merely print out something.

print(1, 2, 3, 4, 5)


print(1, "two", 3.14, true)

You may as well customise the separator character by way of an argument. So if you happen to want a coma character (adopted by an area) in between the weather, you may write one thing like this:

print("a", "b", "c", separator: ", ")

Effectively, in my earlier article you could have seen the way to assemble numerous strings utilizing literals and interpolation, you should use all these variables to print out stuff to the console.

print("""
            __
           / _)
    .-^^^-/ /
 __/       /
<__.|_|-|_|
""")

For instance, this is a cute multi-line ascii artwork dinosaur. πŸ¦•



Debugging and print

Generally it might be cool to know just a bit bit of additional data concerning the printed variable, that is when debugPrint can assist you. The principle distinction between print and debugPrint is that whereas print merely converts every little thing to string, debug print provides you with a short debug data concerning the given objects. The debugPrint technique will print out numbers similar to print does, it’s going to add double quotes round strings, and it will print some additional data about a lot of the different “complicated” sorts.

print(1) 
debugPrint(1) 

print("foo") 
debugPrint("foo") 

print(1...5) 
debugPrint(1...5) 

Truthfully I’ve virtually by no means used this technique, and I at all times most popular print if I needed to print out one thing to the console, but it surely’s at all times good to know that there’s such an choice obtainable built-in to the usual library, nevertheless there’s a technique that can provide you far more data… 🧐



Debugging utilizing dump

The dump technique can print out the given object’s content material utilizing its mirror to the usual output. Lengthy story brief, this operate will present you a extra detailed view concerning the property. For scalar values the dump technique will produce virtually the identical output as debug-print, besides the dump line at all times begins with a splash character, however for extra complicated sorts it’s going to output the underlying construction of the article. Don’t fret, you need not perceive the output of this technique, simply do not forget that it could possibly present you useful data throughout debugging. 🐞

dump(1)
dump(3.14)
dump("foo")
dump(1...5)

The ClosedRange struct is a built-in sort with a lowerBound and an upperBound property. Whereas the print operate solely returned the outlined vary (1…5), the debugPrint technique additionally revealed the kind of the article, dump takes this one step additional by displaying us the precise decrease and higher certain properties of the worth. This may be extraordinarily useful when you could have a posh sort with plenty of underlying properties that you just need to shortly examine for some purpose. πŸ”

By the way in which, debugging is the act of discovering (and resolving) bugs. Bugs are issues in your program code that stop regular operation. Builders can use debugger instruments to run and examine code step-by-step, line by line or per instruction, however most of them are merely placing print statements into the code to see the present state or results of a given operate. πŸ€·β€β™‚οΈ

Dump has just a few extra operate arguments that you may configure:

dump("check", title: "my-variable", indent: 4, maxDepth: 5, maxItems: 5)

You can provide a reputation to every dumped variable, add some additional indentation earlier than the sprint character, specify the utmost depth for descendents and the utmost variety of parts for which to put in writing the total contents. Be at liberty to play with these parameters for some time. πŸ˜‰

As you may see dump is sort of a robust technique, however nonetheless there are different capabilities for logging functions, let me present you one that’s coming from the Goal-C occasions.



NSLog – the legacy logger operate

You probably have ever labored with Goal-C you need to be conversant in the NS prefixes. The NSLog operate can log an error message to the Apple System Log facility console. It is not a part of the Swift normal library, however you must import the Basis framework with a view to use NSLog.

import Basis

NSLog("I am a dinosaur.")


It’s best to know that NSLog will print the present date & time first, then it’s going to show the title of the operating program with the method and thread identifiers and solely then it’s going to print your message.

Simply to be clear, NSLog is coming from the Goal-C period, it isn’t a advisable logging resolution anymore. Additionally it is very gradual and that may trigger some points if you happen to want exactly timed outputs. That is why I do NOT suggest utilizing NSLog in any respect, however you additionally should know that till just a few years in the past there was no higher built-in different for it, I am not judging, simply saying… πŸ˜…




Unified Logging and Exercise Tracing

If you wish to ship log messages on an Apple machine to the unified logging system, you should use the OSLog framework. This new device was launched at WWDC 2016 and not too long ago bought some good API refinements & updates. It’s best to positively verify the OSLog and Unified Logging advisable by Apple article if you wish to study extra about this subject it is a fantastic write up.

My solely concern about this logging API is that it isn’t that common. It really works nice on Apple platforms, however since Swift is an common language if you wish to add Linux and even Home windows assist, this resolution will not be just right for you…





SwiftLog – A Logging API package deal for Swift

This open supply package deal might be simply built-in into your Swift initiatives through the Swift Package deal Supervisor. You simply should set it up as a dependency within the Package deal.swift manifest file or you may hook it utilizing Xcode below the File > Swift Packages menu as an SPM dependency.


import PackageDescription

let package deal = Package deal(
    title: "myProject",
    dependencies: [
        .package(url: "https://github.com/apple/swift-log.git", from: "1.4.0"),
    ],
    targets: [
        .target(name: "myProject", dependencies: [
            .product(name: "Logging", package: "swift-log")
        ])
    ]
)

The utilization is de facto easy. First you must import the Logging framework, then you definitely create a logger and you employ that logger occasion to print out numerous log messages.


import Logging

let logger = Logger(label: "app-identifier")

logger.data("Good day World!")

The next log ranges are supported:

  • hint
  • debug
  • data
  • discover
  • warning
  • error
  • crucial

You may as well connect further logging metadata to the logger, you must verify the readme for more information about this selection. SwiftLog is utilized in many real-world initiatives, reminiscent of Vapor 4 (a server aspect Swift framework), this additionally implies that it really works nice on Linux working techniques. 🐧


Conclusion

If it involves logging, there are a number of good choices to select from. It solely will depend on your wants which one is the perfect, however normally we will say that it’s time to depart behind NSLog, and time to make use of the brand new OSLog framework. If you’re utilizing Swift on non-Apple platform you must think about using the SwiftLog library, which can also be offered by Apple.

Alternatively in case you are simply scratching the floor and you do not want that many choices or log ranges you may merely follow print and dump statements. It is completely superb to debug utilizing these easy methods to start with. Mastering one thing takes time and debuggers might be fairly scary at first sight. Use print as a lot as you want, however at all times attempt to enhance your instruments & data over time, I hope this text provides you a greater view of the obtainable logging instruments. πŸ€“




Leave a Reply