Logging with Swift for Android
This article explains how to implement logging when developing cross-platform native apps using Swift. We will explain the logging options on Swift, and how logging on iOS translates into logging on Android.
Logging with os.log
Section titled “Logging with os.log”In iOS, os.log is part of Apple’s Unified Logging System, introduced in iOS 10 and macOS Sierra. It’s a performant, privacy-aware, structured logging API provided via the os framework.
The Swift code for logging looks something like this:
import os
// Create a custom log categorylet myLog = OSLog(subsystem: "com.scade.MyApp", category: "Networking")
func fetchData() { os_log("Fetching data from the server...", log: myLog, type: .info)
let success = true // Simulate success or failure
if success { os_log("Data fetch succeeded", log: myLog, type: .debug) } else { os_log("Data fetch failed", log: myLog, type: .error) }}Thanks to SCADE Swift for Android toolchain, os.log now works on Android too. We created a thin abstraction layer that logs into Androids logging system. Logs are available through Android’s Logcat tool.
Differences in Logging in iOS and Android
Section titled “Differences in Logging in iOS and Android”Both iOS and Android have similar log levels. Here how the iOS log command translates to the Android log system:
| Purpose | os.log Level (iOS/macOS) | Android Log Level |
|---|---|---|
| Critical failures | .fault | Log.wtf() |
| Serious errors | .error | Log.e() |
| Unexpected behavior | .notice | Log.w() |
| General info | .info | Log.i() |
| Debugging details | .debug | Log.d() |
| Very verbose/debug | (no explicit level) | Log.v() |
Constraints
Section titled “Constraints”Please use classic OSLog class. The new Logger class introduced in macOS 14 is not supported for compatibility reasons. If you like to use it, creating a wrapper class mimicing Logger class should be super easy.
Apple Swift Log
Section titled “Apple Swift Log”In addition to OSLog on Apple, the Apple Swift community came up with a new logging framework Swift-Log that is more flexible and supports different logging backends (DB, DataDog, Splunk,…). Currently, we do not support Swift-Log in SCADE, but support is planned. For now, we believe os.log is a powerful and efficient logging solution.