iOS Swift:将打印和调试打印写入文件 [英] iOS Swift: write print and debug prints into a file

查看:134
本文介绍了iOS Swift:将打印和调试打印写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

晚上,是否可以将所有打印和调试打印保存到文件中?

Evening, is it possible to save in a file all the prints and the debug prints?

即使没有从Xcode启动,我也希望获得我的应用程序执行的日志.

I would like to have the logs of what my application does even when is not launched from Xcode.

我当时正在考虑重写print和debugPrint方法,并将输入内容写入文件中.

I was thinking to override the print and the debugPrint methods and to write the input into a file.

谢谢

推荐答案

Swift标准库中有一些方法:

There are methods in Swift Standard Library:

func print<Target>(_ items: Any..., separator: String = default, terminator: String = default, to output: inout Target) where Target : TextOutputStream

func debugPrint<Target>(_ items: Any..., separator: String = default, terminator: String = default, to output: inout Target) where Target : TextOutputStream

您可以创建一个实现 TextOutputStream 的对象,该对象会将消息保存到您选择的文件中.如果您在代码库中已有打印,这将非常有用.然后,您可以将其他参数添加到它们中.请记住,这些打印将停止记录到标准输出(控制台).

You can create an object that implements TextOutputStream that will save a message to a file of your choice. This is very useful if you already have existing prints in the codebase. You can then just add the additional parameter to them. Remember that those prints will then stop logging to the standard output (console).

打印文档

debugPrint的文档

示例:

final class LogDestination: TextOutputStream {
  private let path: String
  init() {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    path = paths.first! + "/log"
  }

  func write(_ string: String) {
    if let data = string.data(using: .utf8), let fileHandle = FileHandle(forWritingAtPath: path) {
      defer {
        fileHandle.closeFile()
      }
      fileHandle.seekToEndOfFile()
      fileHandle.write(data)
    }
  }
}

然后

// I would probably use Singleton for this
var dest = LogDestination()
print("My test message", to: &dest)

这篇关于iOS Swift:将打印和调试打印写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆