我正在尝试重写我的日志记录类,我想知道如何在 swift 文件中替换PRETTY_FUNCTION或 NSStringFromSelector(_cmd) 以跟踪方法调用?
16 回答
swift 中的特殊文字如下(来自 [the swift guide]
#file
字符串出现的文件的名称。
#line
Int出现的行号。
#column
Int开始的列号。
#function
字符串出现的声明的名称。
在 Swift 2.2b4 之前,这些是
__FILE__
字符串出现的文件的名称。
__LINE__
Int出现的行号。
__COLUMN__
Int开始的列号。
__FUNCTION__
字符串出现的声明的名称。
您可以在日志语句中使用它们,如下所示:
println("error occurred on line \(__LINE__) in function \(__FUNCTION__)")
查看我刚刚发布的一个新库:https ://github.com/DaveWoodCom/XCGLogger
它是 Swift 的调试日志库。
能够使用#function
宏的关键是将它们设置为日志记录函数的默认值。然后编译器将使用预期值填充它们。
func log(logMessage: String, functionName: String = #function) {
print("\(functionName): \(logMessage)")
}
然后只需调用:
log("my message")
它按预期工作,为您提供如下内容:
whateverFunction(): my message
我会使用这样的东西:
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
- 不再使用 Strings 上不可用的 lastPathComponent
- 日志消息是可选的
尝试这个:
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)")
这是我使用的: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)
}
这将仅在调试模式下打印:
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"
对于 Swift 3 及更高版本:
print("\(#function)")
从 Swift 2.2 开始,您可以使用 指定它Literal Expressions
,如Swift Programming Language guide中所述。
所以如果你有一个Logger
结构体,它有一个记录错误发生位置的函数,那么你可以这样调用它:
Logger().log(message, fileName: #file, functionName: #function, atLine: #line)
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).
这是我的看法。
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")}
希望你喜欢。
这将一次性为您提供类和函数名称:
var name = NSStringFromClass(self.classForCoder) + "." + __FUNCTION__
这似乎在 swift 3.1 中工作正常
print("File: \((#file as NSString).lastPathComponent) Func: \(#function) Line: \(#line)")
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")
}
******可能已过时。*******
正如评论中提到的pranav,请使用 Logger for iOS 14+
我发布了一个新库: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
免责声明:这个库是我创建的。
使用 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 就行了。
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)")
}