Lifehack: Making Logging More Convenient in Swift

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.

Visit Now