Polidea / RxBluetoothKit

iOS & OSX Bluetooth library for RxSwift
Apache License 2.0
1.41k stars 366 forks source link

Add a customisation point for injecting a logger in RxBluetoothKit #341

Closed vladcorneci closed 5 years ago

vladcorneci commented 5 years ago

Adds the capability to route the RxBluetoothKit logs in another app by exposing a customisation point. Each custom logger must conform to Logger protocol.

The current functionality remains unchanged unless another logger is injected.

CLAassistant commented 5 years ago

CLA assistant check
All committers have signed the CLA.

minixT commented 5 years ago

Can you also prepare some example how to use custom logger which I can add to the wiki page?

vladcorneci commented 5 years ago

Can you also prepare some example how to use custom logger which I can add to the wiki page?

Sure. 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.