如何将应用程序日志写入文件并获取它们 [英] How to write Application Logs to File and get them
问题描述
我正在iOS开发中迈出第一步,正在寻找一种在iOS中使用日志记录的方法.
I´m taking baby steps in iOS development and searching for a method to use logging in iOS.
我找到了以下有关使用Swift 3进行日志记录的文档: https://developer.apple. com/documentation/os/logging#1682426
I found these docs about logging with swift 3 : https://developer.apple.com/documentation/os/logging#1682426
文档说日志没有保存在磁盘上.获取日志和处理文件的典型方法是什么?
The Docs say that the logs aren´t saved on disk. What is the typical way to get the logs and process the file?
推荐答案
将此文件放入您的项目
//
// 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()
如果您需要记录某些内容,只需使用打印功能,如
and if you need something to be logged, just use print function like
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)
}
在应用程序的文档"文件夹中,您可以找到"log.txt"文件,以后可以对其进行检查.
in your application's 'Documents' folder you could find 'log.txt' file which you could examine later.
在运行我的测试应用程序两次时,内容看起来像
while running my test application twice, the content looks like
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定义为单调类
if you don't like 'globals' define Log as singletone class
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)
这篇关于如何将应用程序日志写入文件并获取它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!