How to write Application Logs to File and get them

前端 未结 2 896
名媛妹妹
名媛妹妹 2020-12-29 13:11

I´m taking baby steps in iOS development and searching for a method to use logging in iOS.

I found these docs about logging with swift 3 : https://developer.apple.co

相关标签:
2条回答
  • 2020-12-29 13:29

    put this file to your project

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

    or

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

    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] 
    

    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
    }
    

    and use it like

    print("started:", Date(), to: &Log.log)
    
    0 讨论(0)
  • 2020-12-29 13:34

    Swift 3.0 version

    Create a new swift file "TextLog.swift" in your project

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

    Initialize the logger at bottom in the AppDelegate.swift file

    var textLog = TextLog()
    

    Use it anywhere in the application like below

    textLog.write("hello")
    
    0 讨论(0)
提交回复
热议问题