Lifehack: Making Logging More Convenient in Swift

Yury Lebedev
2 min readOct 29, 2023

--

Usually, for debugging console output, we use the standard print function. For example, we might want to check whether a method is called or what data is saved somewhere. But there are many other possible use cases. Often, the number of these print statements becomes overwhelming and eventually clutters the console output. A solution to this is to create a separate caseless enum, for example, named Logger.

enum Logger {

// MARK: - Properties
static var isLoggingEnabled = true // Flag to enable/disable logging

}

// MARK: - Methods
extension Logger {

// Method for logging response information
static func logResponse(_ response: URLResponse) {
guard isLoggingEnabled else { return }

if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
log("HTTP Status Code: \(statusCode)")
} else {
log("URL Response: \(response)")
}
}

// Method for logging URLSession error with description
static func logErrorDescription(_ error: Error) {
guard isLoggingEnabled else { return }

print(error.localizedDescription)
}

// General method for logging
static func log(_ message: String) {
guard isLoggingEnabled else { return }

print(message)
}

}

Here we have a basic implementation, plus some additional functionality for URLSession.

Now, instead of print(yourValue), you use Logger.log(yourValue). And when you no longer need to see prints in the console for a while, instead of searching throughout the app to comment them out or delete them, you simply change the flag in Logger:

static var isLoggingEnabled = true

to false. No more console prints with a single move! 😀

Next time, we will discuss why it’s better to use a caseless enum rather than a struct, when it makes sense, and what advantages it offers.

--

--