Disabling NSLog For Production In Swift Project

前端 未结 8 2067
遥遥无期
遥遥无期 2020-12-23 10:26

So this answer Do I need to disable NSLog before release Application? gives a great way to disable NSLog in a production environment, but unfortunately, this solution does n

8条回答
  •  执笔经年
    2020-12-23 10:42

    I agree with uclagamer's answer, which is essentially a souped up print function wrapped in a preprocessor conditional:

    func gLog(@autoclosure object: () -> T, _ file: String = __FILE__, _ function: String = __FUNCTION__, _ line: Int = __LINE__)
        {
        #if DEBUG
            let value = object()
            let stringRepresentation: String
    
            if let value = value as? CustomDebugStringConvertible
                {
                stringRepresentation = value.debugDescription
                }
            else if let value = value as? CustomStringConvertible
                {
                stringRepresentation = value.description
                }
            else
                {
                fatalError("gLog only works for values that conform to CustomDebugStringConvertible or CustomStringConvertible")
                }
    
            let fileURL = NSURL(string: file)?.lastPathComponent ?? "Unknown file"
            let queue = NSThread.isMainThread() ? "UI" : "BG"
            let gFormatter = NSDateFormatter()
            gFormatter.dateFormat = "HH:mm:ss:SSS"
            let timestamp = gFormatter.stringFromDate(NSDate())
    
            print("\(timestamp) \(queue) = \(fileURL) | \(function)[\(line)]: " + stringRepresentation)
        #endif
        }
    

    This is updated for Swift 2.0. All credit goes to Abider Nasir. His original blog post (and linked gist) can be found here:

    http://abizern.org/2015/02/01/debug-logging-in-swift/

    IMPORTANT NOTE: if anyone is struggling to find the "Swift Compiler - Custom Flags section of Build Settings", which has been mentioned many, many times, you need to make sure that "All" build settings are shown, not just the "Basic" build settings, as is the default.

提交回复
热议问题