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

时间:2017-06-14 06:32:22

标签: ios swift logging swift3

我在iOS开发中采取了一些步骤,并在iOS中搜索使用日志记录的方法。

我发现了这些关于使用swift 3进行日志记录的文档:https://developer.apple.com/documentation/os/logging#1682426

文档说日志没有保存在磁盘上。获取日志和处理文件的典型方法是什么?

2 个答案:

答案 0 :(得分:7)

将此文件放入您的项目

@api_view(['GET',])
def my_function_based_list_view(request):
    paginator = PageNumberPagination()
    filtered_set = filters.MyModelFilter(
                       request.GET, 
                       queryset=MyModel.objects.all()
                   ).qs
    context = paginator.paginate_queryset(filtered_set, request)
    serializer = MyModelSerializer(context, many=True)
    return paginator.get_paginated_response(serializer.data)

如果您需要记录某些内容,只需使用

之类的打印功能即可
//
//  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
    }

在您的申请表'文件'您可以找到的文件夹' log.txt'您可以稍后检查的文件。

在运行我的测试应用程序两次时,内容看起来像

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

如果你不喜欢'全局'将Log定义为单线类

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] 

并像

一样使用它
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
}

答案 1 :(得分:3)

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