如何将应用程序日志写入文件并获取它们
我在iOS开发中采取了一些步骤,并在iOS中搜索使用日志记录的方法。
我发现这些关于使用swift 3进行日志记录的文档: https : //developer.apple.com/documentation/os/logging#1682426
文档说日志没有保存在磁盘上。 获取日志和处理文件的典型方法是什么?
把这个文件放到你的项目中
// // log.swift // logtest // import Foundation struct Log: TextOutputStream { func write(_ string: String) { let fm = FileManager.default let log = fm.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("log.txt") if let handle = try? FileHandle(forWritingTo: log) { handle.seekToEndOfFile() handle.write(string.data(using: .utf8)!) handle.closeFile() } else { try? string.data(using: .utf8)?.write(to: log) } } } var logger = Log()
如果您需要记录某些内容,只需使用打印function即可
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. print("started:", Date(), to: &logger) return true }
要么
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. print(#file, #function, "my own text", 1, [1,2], to: &logger) }
在您的应用程序的’Documents’文件夹中,您可以找到’log.txt’文件,您可以在以后查看。
在运行我的测试应用程序两次时,内容看起来像
started: 2017-06-14 09:58:58 +0000 /Users/ivo_vacek/Documents/logtest/logtest/ViewController.swift viewDidLoad() my own text 1 [1, 2] started: 2017-06-14 09:59:15 +0000 /Users/ivo_vacek/Documents/logtest/logtest/ViewController.swift viewDidLoad() my own text 1 [1, 2]
如果你不喜欢’全局’,请将Log定义为单数类
class Log: TextOutputStream { func write(_ string: String) { let fm = FileManager.default let log = fm.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("log.txt") if let handle = try? FileHandle(forWritingTo: log) { handle.seekToEndOfFile() handle.write(string.data(using: .utf8)!) handle.closeFile() } else { try? string.data(using: .utf8)?.write(to: log) } } static var log: Log = Log() private init() {} // we are sure, nobody else could create it }
并使用它
print("started:", Date(), to: &Log.log)
Swift 3.0版
在项目中创建一个新的swift文件“TextLog.swift”
import Foundation struct TextLog: TextOutputStream { /// Appends the given string to the stream. mutating func write(_ string: String) { let paths = FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask) let documentDirectoryPath = paths.first! let log = documentDirectoryPath.appendingPathComponent("log.txt") do { let handle = try FileHandle(forWritingTo: log) handle.seekToEndOfFile() handle.write(string.data(using: .utf8)!) handle.closeFile() } catch { print(error.localizedDescription) do { try string.data(using: .utf8)?.write(to: log) } catch { print(error.localizedDescription) } } } }
在AppDelegate.swift文件中初始化底部的记录器
var textLog = TextLog()
在应用程序的任何位置使用它,如下所示
textLog.write("hello")