Home iOS Development Logging for beginners in Swift

Logging for beginners in Swift

0
Swift

Fundamental output in Swift utilizing print

The very first technique I might like to point out you is the print function. It could write the textual illustration of the given objects to the usual output. In different phrases we are able to merely say that it will possibly print textual content to the display. A lot of the hello word programs make the most of this technique to show the well-known “Hi there world!” message. In Swift, print is kind of a robust technique, since you possibly can cross round a number of objects for printing out plus you possibly can specify a separator string and a terminator parameter. 🤔

print("Hi there World!")

The snippet above will show the Hi there World! textual content adopted by a newline character (\n), it is because the default terminator is all the time a newline. You possibly can override this conduct by offering your personal terminator string.

print("Hi there World!", terminator: "")

In the event 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 will be printed out proper after the “Hi there World!” sentence. In the event you run this system utilizing a Terminal utility, 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 offer a number of objects to the print perform, they are often actually something, print can deal with strings, integers and all types of different variables. Print underneath 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 too can customise the separator character by way of an argument. So in the event you want a coma character (adopted by an area) in between the weather, you possibly can write one thing like this:

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

Nicely, in my previous article you’ve gotten seen find out how to assemble varied strings utilizing literals and interpolation, you need to 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 will be cool to know just a bit bit of additional data concerning the printed variable, that is when debugPrint might help you. The primary distinction between print and debugPrint is that whereas print merely converts every thing to string, debug print offers you a quick debug data concerning the given objects. The debugPrint technique will print out numbers identical to print does, it will add double quotes round strings, and it will print some additional data about a lot of the different “advanced” 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 all the time most popular print if I needed to print out one thing to the console, however it’s all the time good to know that there’s such an choice out there built-in to the usual library, nonetheless there’s a technique that can provide you far more data… 🧐

Debugging utilizing dump

The dump method can print out the given object’s content material utilizing its mirror to the usual output. Lengthy story brief, this perform 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 all the time begins with a splash character, however for extra advanced sorts it will output the underlying construction of the item. Don’t be concerned, you need not perceive the output of this technique, simply do not forget that it will 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 perform solely returned the outlined vary (1…5), the debugPrint technique additionally revealed the kind of the item, 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’ve gotten a posh sort with numerous underlying properties that you simply need to rapidly 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 tools 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 perform. 🤷‍♂️

Dump has a couple of extra perform arguments that you may configure:

dump("take a look at", identify: "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 write down the complete contents. Be happy to play with these parameters for some time. 😉

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

NSLog – the legacy logger perform

In case you have ever labored with Goal-C you have to be accustomed to the NS prefixes. The NSLog perform can log an error message to the Apple System Log facility console. It isn’t a part of the Swift standard library, however you must import the Foundation framework as a way to use NSLog.

import Basis

NSLog("I am a dinosaur.")

You need to know that NSLog will print the present date & time first, then it will show the identify of the working program with the method and thread identifiers and solely then it will print your message.

Simply to be clear, NSLog is coming from the Goal-C period, it’s not a advisable logging resolution anymore. Additionally it is very sluggish and that may trigger some points in the event you want exactly timed outputs. That is why I do NOT recommend using NSLog in any respect, however you additionally must know that till a couple of years in the past there was no higher built-in various for it, I am not judging, simply saying… 😅

Unified Logging and Exercise Tracing

If you wish to ship log messages on an Apple system to the unified logging system, you need to use the OSLog framework. This new device was launched at WWDC 2016 and not too long ago received some good API refinements & updates. You need to undoubtedly examine the OSLog and Unified Logging recommended by Apple article if you wish to study extra about this subject it is a terrific write up.

My solely concern about this logging API is that it’s not 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 give you the results you want…

SwiftLog – A Logging API bundle for Swift

This open source package could be simply built-in into your Swift initiatives by way of the Swift Package Manager. You simply must set it up as a dependency within the Package deal.swift manifest file or you possibly can hook it utilizing Xcode underneath the File > Swift Packages menu as an SPM dependency.


import PackageDescription

let bundle = Package deal(
    identify: "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 basically simple. First you must import the Logging framework, then you definately create a logger and you utilize that logger occasion to print out varied log messages.

import Logging

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

logger.data("Hi there World!")

The next log ranges are supported:

  • hint
  • debug
  • data
  • discover
  • warning
  • error
  • essential

You too can connect further logging metadata to the logger, you must examine the readme for more information about this selection. SwiftLog is utilized in many real-world initiatives, corresponding to Vapor 4 (a server facet Swift framework), this additionally implies that it really works nice on Linux working programs. 🐧

Conclusion

If it involves logging, there are a number of good choices to select from. It solely is determined by your wants which one is the very best, however typically we are able to say that it’s time to go away 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 be supplied by Apple.

Alternatively in case you are simply scratching the floor and you do not want that many choices or log ranges you possibly can merely keep on with print and dump statements. It is completely high quality to debug utilizing these easy strategies at first. Mastering one thing takes time and debuggers could be fairly horrifying at first sight. Use print as a lot as you want, however all the time attempt to enhance your instruments & information over time, I hope this text provides you a greater view of the out there logging instruments. 🤓

Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here