ios 使用swift记录方法签名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24048430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:28:13  来源:igfitidea点击:

Logging Method signature using swift

ioscmdswiftios8

提问by Essa A. Haddad

I am trying to rewrite my logging class and I would like to know how to substitute PRETTY_FUNCTIONor NSStringFromSelector(_cmd) in a swift file in order to track the method calls?

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

回答by Nick

Special literals in swift are as follows (from [the swift guide]

swift 中的特殊文字如下(来自 [the swift guide]

#fileStringThe name of the file in which it appears.

#file字符串出现它的文件的名称。

#lineIntThe line number on which it appears.

#lineInt它出现的行号。

#columnIntThe column number in which it begins.

#columnInt 开始的列号。

#functionStringThe name of the declaration in which it appears.

#functionString它出现的声明的名称。



Prior to Swift 2.2b4, these were

在 Swift 2.2b4 之前,这些是

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

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

__FILE__StringThe name of the file in which it appears.

__FILE__字符串出现它的文件的名称。

__LINE__IntThe line number on which it appears.

__LINE__Int它出现的行号。

__COLUMN__IntThe column number in which it begins.

__COLUMN__Int 开始的列号。

__FUNCTION__StringThe name of the declaration in which it appears.

__FUNCTION__String它出现的声明的名称。

You can use these in logging statements like so:

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

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

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

回答by Dave Wood

Check out a new library I've just published: https://github.com/DaveWoodCom/XCGLogger

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

It's a debug logging library for Swift.

它是 Swift 的调试日志库。

The key to being able to use the #functionmacros, is to set them as default values to your logging function. The compiler will then fill them in using the expected values.

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

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

Then just call:

然后只需调用:

log("my message")

And it works as expected giving you something like:

它按预期工作,为您提供以下内容:

whateverFunction(): my message

More info on how this works: https://www.cerebralgardens.com/blog/entry/2014/06/09/the-first-essential-swift-3rd-party-library-to-include-in-your-project

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

回答by pipacs

I'd use something like this:

我会使用这样的东西:

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

Improvements compared to previous answers:

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

  • Uses NSLog, not print/println
  • Does not use lastPathComponent which is not available on Strings anymore
  • The log message is optional
  • 使用 NSLog,而不是打印/打印
  • 不使用不再在字符串上可用的 lastPathComponent
  • 日志消息是可选的

回答by Chris Prince

Try this:

尝试这个:

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
    }
}

Log using:

记录使用:

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

回答by Esqarrouth

Here is what I used in: https://github.com/goktugyil/QorumLogs
Its like XCGLogger but better.

这是我使用的内容: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)
}

回答by tesla

This will print only in debug mode:

这将仅在调试模式下打印:

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

Result:

结果:

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

回答by Yasir Ali

For Swift 3 and above:

对于 Swift 3 及更高版本:

print("\(#function)")

回答by luizParreira

As of Swift 2.2, you can specify it using Literal Expressions, as described at the Swift Programming Language guide.

从 Swift 2.2 开始,您可以使用 指定它Literal Expressions,如Swift 编程语言指南 中所述

So if you had a Loggerstruct that had a function that logged where the error happened, then you would call it like this:

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

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

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

回答by floohh

This will get you the class and the function name in one go:

这将使您一次性获得类和函数名称:

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

回答by lozflan

this seems to work fine in swift 3.1

这似乎在 swift 3.1 中工作正常

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