为什么 Swift 中的 print() 不将时间戳记为 Objective C 中的 NSLog

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

从 Objective C 的背景来看,当我使用

NSLog()
时,它会在文本前加上日期时间戳,但是当我在 Swift 上使用
print()
时,它只会打印文本

那么有没有办法让它也打印时间戳,或者我做错了什么?

ios objective-c swift nslog
6个回答
64
投票

因为

print
不是
NSLog
。就这么简单。

NSLog
是 Foundation 中的一个日志记录工具,可写入控制台上显示的 Apple 系统日志工具。

print(…)
是 Swift 标准库中的一个打印函数,用于写入标准输出,该输出出现在调试会话中的控制台上。

您可以将

Date()
添加到
print
参数中以打印当前时间和日期。 (或者
Date().description(with: Locale.current)
以获取您当地时区的信息。)

或者你也可以使用

NSLog
,它在 Swift 中也可用(如果你导入 Foundation)。


36
投票

斯威夫特:

NSLog("this will print with dates")

12
投票

这个仅输出一个简单的时间戳,但如果需要,可以轻松修改以包含其他文本。

此外,它还依赖于

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)

8
投票

这里是一个建议的函数,您可以使用它来代替 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!)
    }
}

3
投票

iOS 14+

新 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)

2
投票

创建您自己的打印类函数,例如 printWithDate() 并将日期添加到输出中。然后您可以在任何地方使用它,而无需每次打印时添加日期。

© www.soinside.com 2019 - 2024. All rights reserved.