emaloney / CleanroomLogger

CleanroomLogger provides an extensible Swift-based logging API that is simple, lightweight and performant
MIT License
1.33k stars 154 forks source link

Custom logger wrapper not showing correct line number #78

Closed wongzigii closed 7 years ago

wongzigii commented 7 years ago

So far I had created a custom logger wrapper, so I call QLog.info() where I want. So far so good, However, the console keeps showing the line number of my wrapper:

wx20170428-173327

Here is my warpper:

import CleanroomLogger

struct QLog {

    static let shared = QLog()

    static func setup() {
        CleanroomLogger.Log.enable()

        self.info("CleanroomLogger is now enable!")
    }

    static func error(_ text: String) {
        CleanroomLogger.Log.error?.message(text)
    }

    static func debug(_ text: String) {
        CleanroomLogger.Log.debug?.message(text)
    }

    static func warning(_ text: String) {
        CleanroomLogger.Log.warning?.message(text)
    }

    static func verbose(_ text: String) {
        CleanroomLogger.Log.verbose?.message(text)
    }

    static func info(_ text: String) {
        CleanroomLogger.Log.info?.message(text)
    }
}

Is this an expected behavior?

emaloney commented 7 years ago

Yes, this behavior is expected because CleanroomLogger shows the source file and line number of the call site—the place where you call a function like message(), trace() or value().

However, you can modify your code to capture the source file and line number where your wrapper is called and pass that along to CleanroomLogger.

If you look at the declaration for the message() function:

public func message(_ msg: String, function: String = #function, filePath: String = #file, fileLine: Int = #line)

you'll notice the function, filePath and fileLine parameters with default values. Normally you don't provide these values, but this is how CleanroomLogger figures out where it is being called from.

You can use the same technique in your wrapper to pass down the appropriate values.

For example, your error() function could be rewritten as:

static func error(_ text: String, function: String = #function, filePath: String = #file, fileLine: Int = #line) {
    CleanroomLogger.Log.error?.message(text, function: function, filePath: filePath, fileLine: fileLine)
}

Then, you'll see the call site you expect when you call QLog.shared.error(). And you won't need to modify any of the callers of your QLog functions; the magic of default parameter values takes care of everything for you.

Hope this helps, E.

wongzigii commented 7 years ago

Thanks so much!