Write a log text file on Disk use TextOutputStream in Swift 4 iOS

i0S Swift Issue

You need to create your own log file to record events in your application in your own way. Here is the most typical way to create a text file and save it on the disk of an iOS device like iPhone, iPad, iPod.

struct Log: TextOutputStream {
    func write(_ string: String) {
        let dFormatter = DateFormatter()
        dFormatter.dateFormat = "yyyy-MM-"
        let date = Date()
        let currentMonth = dFormatter.string(from: date)
        
        let fm = FileManager.default
        let log = fm.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(String(currentMonth) + "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)
        }
    }
}

Using:

1. Declare logger variable with Log() type

var logger = Log()

2. If you need something to be logged, just use print function like this:

print("Something Here", to: &logger)

Example:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    print(#file, #function, "Something Here", to: &logger)
}

A literal expression consists of either an ordinary literal (such as a string or a number), an array or dictionary literal, a playground literal, or one of the following special literals:

Literal Type Value
#file String The name of the file in which it appears.
#line Int The line number on which it appears.
#column Int The column number in which it begins.
#function String The name of the declaration in which it appears.
#dsohandle UnsafeRawPointer The DSO (dynamic shared object) handle in use where it appears.