Remote error #logging with #Swift
When you are running your app in the simulator, or attached via USB, you can see your error messages in the debugger, but whenever your app is in the wild, or even on your client’s phone (Or Apple’s testing department) – you can no longer easily see your debug messages, to understand technically, what’s happening in your app.
Remote error logging isn’t new, and you can even knock a simple remote logging mechanism up your self with a little server-side code, but this should make the process super easy for you.
Firstly, Create an Account on “RemoteLogCat.com” and then you get an API key back, then add the following class to your Swift App:
import Foundation
class Logging
{
static var Key : String?
static func Log(Channel : String, Log : String, Completion: ((Bool) -> ())? = nil)
{
if let apiKey = Logging.Key
{
let strChannel = Channel.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let strLog = Log.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
print(“\(Channel):\(Log)”)
let url = URL(string: “http://www.remotelogcat.com/log.php?apikey=\(apiKey)&channel=\(strChannel)&log=\(strLog)”)
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
Completion?(error == nil)
}
task.resume()
}
else
{
print(“No API Key set for RemoteLogCat.com API”)
Completion?(false)
}
}
}
Then you can simply Log errors to the service using the code:
Logging.Key = “……”
Logging.Log(Channel: “macOS”, Log: “Hello Log!”)
Obviously Logging.Key only needs to be set once, and be aware, that this is an asynchronous method, so if your application terminates immediately afterwards, then nothing will be logged.
You can get a completion handler, by adding
Logging.Log(Channel: “macOS”, Log: “Hello Log!”) {
print(“Success: \($0)”)
}
Where the argument to the completion handler is a Boolean indicating success or failure (i.e. no internet)