Debugging an application is something we do very often. That is normal.
When some error occurs, we want for our users to find it, right? Of course not. We want to be able to fix it as soon as possible and to avoid that scenario.
But, how can we make this process easy for us? We can build a tiny logger so that if some error occurs we can see in which function it happened, on which line, which column, etc. That would be nice, right? Let’s do it.
First things first, let’s define our enum with the possible options:
Next, we have to build our class which will work together with our enum:
We defined our dateFormatter because when we do the actual logging, we want to put a date when it is written.
Next, we have our class function, called log, which accepts a couple of parameters:
- message – it’s a human readable message
- type – that is our enum
- fileName – file name in which the log occurred, for example, AppDelegate.swift
- line – as the name implies the line in which our log occurred
- column – the column in which our log occurred
- function – what function called our Logger
Of course, we need that log message only when we’re in DEBUG mode. If the app is on the App Store, we’re not able to see our log console, so we don’t need those log messages at all. We can use some other libraries for that. That’s the reason why print() function is wrapped with that #if DEBUG.
sourceFileName function will extract the file name from the file path. The reason for this is because we don’t need the whole path:
we only need that last part – AppDelegate.swift
At the very end, we made a small extension where we will use our dateFormatter to generate a date for those logs.
Finally, let’s test it inside Playground as well as in our Xcode project:
You will find the full source code on GitHub.