日志

日志提供了一种将信息记录到控制台和文件的方法。它提供了 Log.print() 方法,该方法只需要对您的代码进行最少的更改,因为您可能已经在使用 Swift.print() 了。

示例

这会在默认的日志目录 (path/to/application-support-dir/Logs) 中创建一个文件日志输出,其名称包含当前月份和年份(例如,2018 年 10 月的 log-2018-10.txt)。

guard let dirURL = Logging.defaultLogsDirectoryURL() else {
	Swift.print("Logs directory not found")
	return
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "y-MM"

let fileName = "log-\(dateFormatter.string(from: Date()))"
let fileURL = dirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
let output = FileOutput(filePath: fileURL.path)
Logger.sharedInstance.addOutput(output)

Swift.print("Log file placed at \(fileURL.path)")

然后,您可以开始使用 Log.print() 进行日志记录。

Log.print("Ups, something went wrong")

日志文件将如下所示

2018-10-29 12:27:11.050 Ups, something went wrong

附加到电子邮件

如果用户报告了您的应用程序存在问题,您可以像这样将日志文件附加到电子邮件。

以下示例使用最近的 2 个日志文件并将它们附加到邮件撰写表单。

let mailController = MFMailComposeViewController()
if let urls = Logging.fileURLs { // returns the log files sorted by the creation date
	let fileManager = FileManager()
	for url in urls.prefix(2) {
		guard let data = fileManager.contents(atPath: url.path) else {
			continue
		}
		// Attach log as text file
		mailController.addAttachmentData(data, mimeType: "text/plain", fileName: url.lastPathComponent)
	}
}