Skip to content

10. Logging

Michał Laskowski edited this page Jul 26, 2019 · 1 revision

RxBluetoothKit provide some logs, which can be used to debug Bluetooth connection. By default logs are disabled and to enable them you need to set required log level. For example to display all logs you should call:

RxBluetoothKitLogger.defaultLogger.setLogLevel(.verbose)

Custom logger

A custom logger can be created by simply implementing the Logger protocol which specifies two logging methods and log level getters and setters.

For example, we can create a simple logger which counts the number of logs for each log level.

private class SimpleCountLogger: Logger {
    private var logCount: [UInt]

    private var currentLogLevel: RxBluetoothKitLog.LogLevel = .verbose

    init() {
        logCount = [UInt](repeating: 0, count: Int(UInt8.max))
    }

    public func getLogCount() -> [UInt] {
        return logCount
    }

    public func setLogLevel(_ logLevel: RxBluetoothKitLog.LogLevel) {
        self.currentLogLevel = logLevel
    }

    public func getLogLevel() -> RxBluetoothKitLog.LogLevel {
        return currentLogLevel
    }

    func log(
        _ message: @autoclosure () -> String,
        level: RxBluetoothKitLog.LogLevel,
        file: StaticString,
        function: StaticString,
        line: UInt
    ) {
        log(
            message(),
            level: level,
            file: String(describing: file),
            function: String(describing: function),
            line: line
        )
    }

    func log(
        _ message: @autoclosure () -> String,
        level: RxBluetoothKitLog.LogLevel,
        file: String,
        function: String,
        line: UInt
    ) {
        logCount[Int(level.rawValue)] += 1
    }
}

After this, one can simply inject it into the library by modifying RxBluetoothKitLogger.defaultLogger variable. A good place for injecting it can be the AppDelegate.swift.