LoginSignup
0
0

【Swift】シンプルにログをファイルに書き出す

Posted at

コピペでいけます

ソース

logger.swift
import Foundation
import UIKit


///
///
/// 日時用書式インスタンス
///
///
private class __formatInstance {

    private static var _formatter : DateFormatter?
    
    static var formatter : DateFormatter {
        get {
            if ( _formatter == nil  ){
                _formatter = DateFormatter()
                _formatter!.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS "
            }
            return _formatter!
        }
    }
}

func dateString() -> String {
    return __formatInstance.formatter.string(from:Date())
}

func printLog(_ log: Any) {

    let timestamp = __formatInstance.formatter.string(from:Date())
    print(timestamp, terminator: "")
    let tid = Thread.current

    let logStr = log as? String
    if let str = logStr {
        print("\(tid) : \(str)")
        Logger.getInstance().write(timeStamp: timestamp, text: "\(tid) : \(str)")
    }else{
        print("CAN'T LOG WRITE")
    }
}

class Logger {
    
    private let filename_ : String
    
    private static let instance_ = Logger()
    
    init(){
        
        let date = Date()

        let df = DateFormatter()
        
        df.dateFormat = "yyyyMMddHHmmss"
        self.filename_ = "Log_\(df.string(from: date)).log"
        
        print("log filename:\(self.filename_)")
    }
    
    
    static func getInstance() -> Logger{
        return Logger.instance_
    }

    func write(timeStamp tm: String,  text:String)
    {
        /// DocumentsフォルダURL取得
        guard let dirURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            fatalError("フォルダURL取得エラー")
        }
        /// 対象のファイルURL取得
        let fileURL = dirURL.appendingPathComponent( self.filename_ )
        if self.write(url: fileURL, text: "\(tm) \(text)") == false{
            printLog("LOG ERROR")
        }
    }
    
    func write(_ text:String)
    {
        let logTimeStamp = __formatInstance.formatter.string(from:Date())

        self.write(timeStamp:logTimeStamp,  text:text)
    }
    
    func write(url: URL, text: String) -> Bool {
        guard let stream = OutputStream(url: url, append: true) else {
            return false
        }
        stream.open()
        
        defer {
            stream.close()
        }
        
        let logText = "\(text)\n"
        
        guard let data = logText.data(using: .utf8) else { return false }
        let byteArray = [UInt8](data)
        let result = stream.write(byteArray , maxLength: byteArray.count)
        return (result > 0)
    }

}

つかいかた

Logger.getInstance().write("test")

ファイルを確認

  1. Window > Devices and Simulators
  2. デバッグ中のiPhone > デバッグ中のApp > [...] > Download Container...
  3. できたContainerを右クリック > パッケージの内容を表示 > AppData > Documents
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0