使用 swift 记录方法签名

问题描述 投票:0回答:17

我正在尝试重写我的日志记录类,我想知道如何在 swift 文件中替换 PRETTY_FUNCTION 或 NSStringFromSelector(_cmd) 以跟踪方法调用?

ios cmd swift ios8
17个回答
97
投票

Swift 中的特殊文字如下(来自 [Swift 指南]

#file
String 它所在的文件的名称。

#line
Int 它出现的行号。

#column
Int 开始的列号。

#function
String 它出现的声明的名称。


在 Swift 2.2b4 之前,这些是

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html)):

__FILE__
String 它出现的文件的名称。

__LINE__
Int 它出现的行号。

__COLUMN__
Int 开始的列号。

__FUNCTION__
String 它出现的声明的名称。

您可以在日志语句中使用它们,如下所示:

println("error occurred on line \(__LINE__) in function \(__FUNCTION__)")


64
投票

查看我刚刚发布的新库:https://github.com/DaveWoodCom/XCGLogger

它是 Swift 的调试日志库。

能够使用

#function
宏的关键是将它们设置为日志记录功能的默认值。然后编译器将使用预期值填充它们。

func log(logMessage: String, functionName: String = #function) {
    print("\(functionName): \(logMessage)")
}

那就拨打:

log("my message")

它按预期工作,给你类似的东西:

whateverFunction(): my message

有关其工作原理的更多信息:https://www.cerebralgardens.com/blog/entry/2014/06/09/the-first-essential-swift-3rd-party-library-to-include-in-your -项目


9
投票

我会用这样的东西:

func Log(message: String = "", _ path: String = __FILE__, _ function: String = __FUNCTION__) {
    let file = path.componentsSeparatedByString("/").last!.componentsSeparatedByString(".").first! // Sorry
    NSLog("\(file).\(function): \(message)")
}

与之前的答案相比的改进:

  • 使用 NSLog,而不是 print/println
  • 不使用在字符串上不再可用的lastPathComponent
  • 日志消息是可选的

5
投票

试试这个:

class Log {
    class func msg(message: String,
        functionName:  String = __FUNCTION__, fileNameWithPath: String = __FILE__, lineNumber: Int = __LINE__ ) {
        // In the default arguments to this function:
        // 1) If I use a String type, the macros (e.g., __LINE__) don't expand at run time.
        //  "\(__FUNCTION__)\(__FILE__)\(__LINE__)"
        // 2) A tuple type, like,
        // typealias SMLogFuncDetails = (String, String, Int)
        //  SMLogFuncDetails = (__FUNCTION__, __FILE__, __LINE__) 
        //  doesn't work either.
        // 3) This String = __FUNCTION__ + __FILE__
        //  also doesn't work.

        var fileNameWithoutPath = fileNameWithPath.lastPathComponent

#if DEBUG
        let output = "\(NSDate()): \(message) [\(functionName) in \(fileNameWithoutPath), line \(lineNumber)]"
        println(output)
#endif
    }
}

登录使用:

let x = 100
Log.msg("My output message \(x)")

5
投票

这是我使用的:https://github.com/goktugyil/QorumLogs
它类似于 XCGLogger,但更好。

func myLog<T>(object: T, _ file: String = __FILE__, _ function: String = __FUNCTION__, _ line: Int = __LINE__) {
    let info = "\(file).\(function)[\(line)]:\(object)"
    print(info)
}

4
投票

这只会在调试模式下打印:

func debugLog(text: String,  fileName: String = __FILE__, function: String =  __FUNCTION__, line: Int = __LINE__) {
    debugPrint("[\((fileName as NSString).lastPathComponent), in \(function)() at line: \(line)]: \(text)")
}

结果:

"[Book.swift, in addPage() at line: 33]: Page added with success"

4
投票

对于 Swift 3 及以上版本:

print("\(#function)")

4
投票

Swift 4,基于所有这些很棒的答案。 ❤️

/*
 That's how I protect my virginity.
*/

import Foundation

/// Based on [this SO question](https://stackoverflow.com/questions/24048430/logging-method-signature-using-swift).
class Logger {

    // MARK: - Lifecycle

    private init() {} // Disallows direct instantiation e.g.: "Logger()"

    // MARK: - Logging

    class func log(_ message: Any = "",
                   withEmoji: Bool = true,
                   filename: String = #file,
                   function: String =  #function,
                   line: Int = #line) {

        if withEmoji {
            let body = emojiBody(filename: filename, function: function, line: line)
            emojiLog(messageHeader: emojiHeader(), messageBody: body)

        } else {
            let body = regularBody(filename: filename, function: function, line: line)
            regularLog(messageHeader: regularHeader(), messageBody: body)
        }

        let messageString = String(describing: message)
        guard !messageString.isEmpty else { return }
        print(" └ 📣 \(messageString)\n")
    }
}

// MARK: - Private

// MARK: Emoji

private extension Logger {

    class func emojiHeader() -> String {
        return "⏱ \(formattedDate())"
    }

    class func emojiBody(filename: String, function: String, line: Int) -> String {
        return "🗂 \(filenameWithoutPath(filename: filename)), in 🔠 \(function) at #️⃣ \(line)"
    }

    class func emojiLog(messageHeader: String, messageBody: String) {
        print("\(messageHeader) │ \(messageBody)")
    }
}

// MARK: Regular

private extension Logger {

    class func regularHeader() -> String {
        return " \(formattedDate()) "
    }

    class func regularBody(filename: String, function: String, line: Int) -> String {
        return " \(filenameWithoutPath(filename: filename)), in \(function) at \(line) "
    }

    class func regularLog(messageHeader: String, messageBody: String) {
        let headerHorizontalLine = horizontalLine(for: messageHeader)
        let bodyHorizontalLine = horizontalLine(for: messageBody)

        print("┌\(headerHorizontalLine)┬\(bodyHorizontalLine)┐")
        print("│\(messageHeader)│\(messageBody)│")
        print("└\(headerHorizontalLine)┴\(bodyHorizontalLine)┘")
    }

    /// Returns a `String` composed by horizontal box-drawing characters (─) based on the given message length.
    ///
    /// For example:
    ///
    ///     " ViewController.swift, in viewDidLoad() at 26 " // Message
    ///     "──────────────────────────────────────────────" // Returned String
    ///
    /// Reference: [U+250x Unicode](https://en.wikipedia.org/wiki/Box-drawing_character)
    class func horizontalLine(for message: String) -> String {
        return Array(repeating: "─", count: message.count).joined()
    }
}

// MARK: Util

private extension Logger {

    /// "/Users/blablabla/Class.swift" becomes "Class.swift"
    class func filenameWithoutPath(filename: String) -> String {
        return URL(fileURLWithPath: filename).lastPathComponent
    }

    /// E.g. `15:25:04.749`
    class func formattedDate() -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm:ss.SSS"
        return "\(dateFormatter.string(from: Date()))"
    }
}

使用

Logger.log()
拨打电话 --(表情符号默认开启):


Logger.log(withEmoji: false)
打电话:


更多使用示例:

Logger.log()
Logger.log(withEmoji: false)
Logger.log("I'm a virgin.")
Logger.log("I'm a virgin.", withEmoji: false)
Logger.log(NSScreen.min.frame.maxX) // Can handle "Any" (not only String).

3
投票

从 Swift 2.2 开始,您可以使用

Literal Expressions
指定它,如 Swift 编程语言指南中所述。

因此,如果您有一个

Logger
结构体,其中有一个记录错误发生位置的函数,那么您可以这样调用它:

Logger().log(message, fileName: #file, functionName: #function, atLine: #line)


3
投票

这是我的看法。

func Log<T>(_ object: Shit, _ file: String = #file, _ function: String = #function, _ line: Int = #line) {

var filename = (file as NSString).lastPathComponent
filename = filename.components(separatedBy: ".")[0]

let currentDate = Date()
let df = DateFormatter()
df.dateFormat = "HH:mm:ss.SSS"

print("┌──────────────┬───────────────────────────────────────────────────────────────")
print("│ \(df.string(from: currentDate)) │ \(filename).\(function) (\(line))")
print("└──────────────┴───────────────────────────────────────────────────────────────")
print("  \(object)\n")}

希望您喜欢。


2
投票

这将一次性为您提供类和函数名称:

var name = NSStringFromClass(self.classForCoder) + "." + __FUNCTION__

2
投票

这似乎在 swift 3.1 中工作得很好

print("File: \((#file as NSString).lastPathComponent) Func: \(#function) Line: \(#line)")

1
投票

Swift 3 支持带有日期、函数名、文件名、行号的 debugLog 对象:

public func debugLog(object: Any, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
    let className = (fileName as NSString).lastPathComponent
    print("\(NSDate()): <\(className)> \(functionName) [#\(lineNumber)]| \(object)\n")
}

1
投票

****** 可能已经过时了。 ******

正如 pranav 在评论中提到的,请使用适用于 iOS 14+ 的 Logger


我发布了一个新库:Printer

它有很多功能让您以不同的方式登录。

记录成功消息:

Printer.log.success(details: "This is a Success message.")

输出:

Printer ➞ [✅ Success] [⌚04-27-2017 10:53:28] ➞ ✹✹This is a Success message.✹✹
[Trace] ➞ ViewController.swift ➞ viewDidLoad() #58

免责声明:这个库是我创建的。


0
投票
func Log<T>(_ object: T, fileName: String = #file, function: String =  #function, line: Int = #line) {
    NSLog("\((fileName as NSString).lastPathComponent), in \(function) at line: \(line): \(object)")
}

0
投票

使用 os_log 的替代版本可能是:

func Log(_ msg: String = "", _ file: NSString = #file, _ function: String = #function) {
    let baseName = file.lastPathComponent.replacingOccurrences(of: ".swift", with: "")
    os_log("%{public}@:%{public}@: %@", type: .default, baseName, function, msg)
}

仍然对字符串处理很重,如果你负担不起,直接使用 os_log 即可。


0
投票

对于 iOS 14.0 及更高版本,使用 Logger,它将显示文件和行号,并且还允许您跳转到代码中的该行:

但是有时它不起作用,我必须使用解决方法来显示文件和行号(在类别元数据下),以便我可以在调试时手动转到那里:

  import OSLog
    import SecureIdentityInterface
    import TransmitSDK3
    
    public extension Logger {
        init(metadata _: Bool, _ file: StaticString = #fileID, _ line: Int = #line) {
            self.init(subsystem: Bundle.main.bundleIdentifier ?? "", category: "\(file) \(line)")
        }
    }

用途:

import OSLog
Logger(metadata: true).error("Error: \(error)") 

布尔值并不重要,它只是将其路由到我们的 Logger init。

最后要在 Xcode 控制台中查看它,请启用屏幕底部的元数据类别:

您的最终结果将是: 请注意类别元数据,其中显示了我们在上面添加的文件和行号。

否则我们可以只使用 Logger 的本机 init,但有时它可能没有文件和行信息(希望 Apple 将来修复它)。

import OSLog
Logger().error("Error: \(error)") 
© www.soinside.com 2019 - 2024. All rights reserved.