Updated 19 February 2018
Hi Guyz , Today we will learn about “How to create logs in swift ?”.
Sometimes we need to solve a major issue at client end which got skipped in our testing. Thus if our client provides a log file regarding the issue then this would be very helpful for us.
For this purpose we need to provide a log generating application to the client that will generate the log file after a successful event.
We will create a SwiftLoggor class which will handle all the log generation process.
First copy the below code into your class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
static var dateFormat = "yyyy-MM-dd hh:mm:ssSSS" static var fileContent = "" static var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = dateFormat formatter.locale = Locale.current formatter.timeZone = TimeZone.current return formatter } private class func sourceFileName(filePath: String) -> String { let components = filePath.components(separatedBy: "/") return components.isEmpty ? "" : components.last! } class func log(message: String, // 1. event: ErroTypes, // 2. fileName: String = #file, // 3. line: Int = #line, // 4. column: Int = #column,// 5. funcName: String = #function) -> String{ return "\(Date().toString()) \(event.rawValue)[\(sourceFileName(filePath: fileName))]:\(line) \(column)\(funcName) -> \(message)" } class func writeToFile(message: String){ let filename = SwiftLoggor.getDocumentsDirectory().appendingPathComponent("Log.txt") do { try message.write(to: filename, atomically: true, encoding: String.Encoding.utf8) } catch { print("Some error occur") } } class func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return paths[0] } |
We will also create a date extension like this
1 2 3 4 5 |
extension Date { func toString() -> String { return SwiftLoggor.dateFormatter.string(from: self as Date) } } |
We will define our log cases like this.
1 2 3 4 5 6 7 8 |
enum ErroTypes : String{ case e = "[‼]" // error case i = "[ℹ]" // info case d = "[💬]" // debug case v = "[🔬]" // verbose case w = "[⚠]" // warning case s = "[🔥]" // severe } |
Your class will look like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
class SwiftLoggor { static var dateFormat = "yyyy-MM-dd hh:mm:ssSSS" static var fileContent = "" static var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = dateFormat formatter.locale = Locale.current formatter.timeZone = TimeZone.current return formatter } private class func sourceFileName(filePath: String) -> String { let components = filePath.components(separatedBy: "/") return components.isEmpty ? "" : components.last! } class func log(message: String, // 1. event: ErroTypes, // 2. fileName: String = #file, // 3. line: Int = #line, // 4. column: Int = #column,// 5. funcName: String = #function) -> String{ return "\(Date().toString()) \(event.rawValue)[\(sourceFileName(filePath: fileName))]:\(line) \(column)\(funcName) -> \(message)" } class func writeToFile(message: String){ let filename = SwiftLoggor.getDocumentsDirectory().appendingPathComponent("Log.txt") do { try message.write(to: filename, atomically: true, encoding: String.Encoding.utf8) } catch { print("Some error occur") } } class func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return paths[0] } } |
Now lets dive into the code to see whats happening over here ,
1 |
static var dateFormat = "yyyy-MM-dd hh:mm:ssSSS" |
dateFormat variable to represent the date format. You can create your own.
1 |
static var fileContent = "" |
fileContent variable will store all your logs to be written in the log file.
1 |
static var dateFormatter: DateFormatter |
A dateFormatter variable in which the locale and timezone are according to the device’s current locale and timezone.
The sourceFileName will provide the file name in which we are placing the log.
You need to know about these literals
The log function will take a log message and event of ErroTypes as parameters and will return a string which will include the above literal results like line and column number of the log , file and function name in which the log appears and date.
The writeToFile function allow us to write the log into a text file named “Log.txt” in our app’s documents directory.
Note:- Whenever we call writeToFile it will overwrite the previous generated log file. Thus try to call it once in the application with complete logs stored in a separate variable , here we are using fileContent.
The function getDocumentsDirectory will return the url of documents directory.
You can store all your logs into fileContent variable and then pass it to writeToFile function in your applicationWillTerminate function . inside Appdelegate.
Store your logs like this
1 |
SwiftLoggor.fileContent = "\n \(SwiftLoggor.log(message:"My first log",event:ErroTypes.e))" |
to print your log use
1 |
print(SwiftLoggor.log(message:"My first log",event:ErroTypes.e) |
Now in your applicationWillTerminate put this
1 |
SwiftLoggor.writeToFile(message:Swiftloggor.fileContent) |
Now you have all your logs into your Log file. Here are the steps to how to get your log file from the documents directory of your app.
Note:- Your app’s info.plist must include UIFileSharingEnabled key with its value as “Yes”.
that how you will get your log file.
Thats all guys enjoy! .
You can take detailed reference from this blog
https://medium.com/@sauvik_dolui/developing-a-tiny-logger-in-swift-7221751628e6
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.