Lifehack: Making Logging More Convenient in Swift

<p>Usually, for debugging console output, we use the standard&nbsp;<code>print</code>&nbsp;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&nbsp;<code>Logger</code>.</p> <pre> 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(&quot;HTTP Status Code: \(statusCode)&quot;) } else { log(&quot;URL Response: \(response)&quot;) } } // 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) } }</pre> <p>Here we have a basic implementation, plus some additional functionality for&nbsp;<code>URLSession</code>.</p> <p><a href="https://medium.com/@quasaryy/lifehack-making-logging-more-convenient-in-swift-5bb5fc5e3a97"><strong>Visit Now</strong></a></p>