从 Objective C 的背景来看,当我使用
NSLog()
时,它会在文本前加上日期时间戳,但是当我在 Swift 上使用 print()
时,它只会打印文本
那么有没有办法让它也打印时间戳,或者我做错了什么?
斯威夫特:
NSLog("this will print with dates")
这个仅输出一个简单的时间戳,但如果需要,可以轻松修改以包含其他文本。
此外,它还依赖于
lazy
DateFormatter
来避免昂贵的初始化。
import Foundation
class Timestamp {
lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS "
return formatter
}()
func printTimestamp() {
print(dateFormatter.string(from: Date()))
}
}
let timestamp = Timestamp()
timestamp.printTimestamp() // 2018-07-05 12:57:08.725
timestamp.printTimestamp() // 2018-07-05 12:57:08.727 (uses the same formatter)
这里是一个建议的函数,您可以使用它来代替 print()
func printLog(log: AnyObject?) {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS "
print(formatter.stringFromDate(NSDate()), terminator: "")
if log == nil {
print("nil")
}
else {
print(log!)
}
}
新 API
os.Logger.log
,带有可选 level
参数:https://developer.apple.com/documentation/os/logger/3551622-log
import os.Logger
log("Message \(var)")
log(level: .debug, "Message \(var)")
您可以使用
Logging
os 模块在 Swift 中执行此操作:https://developer.apple.com/documentation/os/logging
具体
os_log
:https://developer.apple.com/documentation/os/2320718-os_log
import os.log
os_log("Message %d", type: .info, value)
创建您自己的打印类函数,例如 printWithDate() 并将日期添加到输出中。然后您可以在任何地方使用它,而无需每次打印时添加日期。