使用swift记录方法签名

Ess*_*dad 49 cmd ios swift ios8

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

Nic*_*ick 89

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__)")


Dav*_*ood 59

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

它是Swift的调试日志库.

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

func log(logMessage: String, functionName: String = #function) {
    print("\(functionName): \(logMessage)")
}
Run Code Online (Sandbox Code Playgroud)

然后打电话:

log("my message")
Run Code Online (Sandbox Code Playgroud)

它按预期工作,给你一些像:

whateverFunction(): my message
Run Code Online (Sandbox Code Playgroud)

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


pip*_*acs 9

我会用这样的东西:

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

与以前的答案相比有所改进:

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


Chr*_*nce 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
    }
}
Run Code Online (Sandbox Code Playgroud)

使用日志:

let x = 100
Log.msg("My output message \(x)")
Run Code Online (Sandbox Code Playgroud)


Esq*_*uth 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)
}
Run Code Online (Sandbox Code Playgroud)