ios - 如何将应用程序日志写入文件并获取它们

标签 ios swift logging oslog

我在 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()

如果你需要记录一些东西,只需使用类似打印的功能

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] 

如果您不喜欢'globals',请将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)

关于ios - 如何将应用程序日志写入文件并获取它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44537133/

相关文章:

python - 在 Python Pyramid 单元测试中查看日志输出

ios - UITableViewCell 中文本字段的值 - iOS ObjC

ios - Swift 3.0 无法将 (_, _)->() 类型的值转换为预期参数类型 'ObjectsOrErrorBlock'

ios - 如何在运行时在IOS项目中添加Resource

objective-c - Core Data迁移后如何保持数据排序?

python - Django 日志记录项目和应用程序命名空间

ios - 主 - 详细项目未按预期工作

ios - UITableView 的交互部分标题

ios - AVAudioRecorder 不工作

python - 我如何在 iPython 0.12 中自动启用日志记录 *with timestamps*?