Last active
October 16, 2017 05:56
-
-
Save vhart/09c5afb2ab2bc7998191de63968e8eb7 to your computer and use it in GitHub Desktop.
Logger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BasicLogger: NSObject { | |
private static let queue = dispatch_queue_create("com.vhart.BasicLoggerQueue", DISPATCH_QUEUE_SERIAL) | |
private static let dateFormatter = NSDateFormatter() | |
static var filePath: String { | |
return fileUrl.path! | |
} | |
static var fileUrl: NSURL { | |
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) | |
let documentsDirectory = paths[0] as NSString | |
return NSURL(fileURLWithPath: documentsDirectory.stringByAppendingPathComponent("LogFile.txt"), isDirectory: false) | |
} | |
override init() { | |
fatalError() | |
} | |
// For Obj-C compatability | |
// | |
// Convert __FILE__ using [NSString stringWithFormat:@"%s", __FILE__ | |
// Same for __FUNCTION__ | |
// | |
// [BasicLogger objcWriteFile: [NSString stringWithFormat:@"%s", __FILE__] | |
// function: [NSString stringWithFormat:@"%s", __FUNCTION__] | |
// line: __LINE__ | |
// message: @"Example message"]; | |
// | |
class func objcWriteFile(file: String, | |
function: String, | |
line: Int, | |
message: String) { | |
objc_sync_enter(self) | |
defer { objc_sync_exit(self) } | |
let fileName = (file as NSString).lastPathComponent | |
write("\(fileName) \(function): \(line): -- \(message)") | |
} | |
class func write(file: String = #file, | |
function: String = #function, | |
line: Int = #line, | |
message: String) { | |
objc_sync_enter(self) | |
defer { objc_sync_exit(self) } | |
let fileName = (file as NSString).lastPathComponent | |
write("\(fileName) \(function): \(line): -- \(message)") | |
} | |
private class func write(str: String) { | |
dispatch_async(queue) { | |
dateFormatter.dateFormat = "MM-dd-yyyy'| 'HH:mm:ss +SSS'|'" | |
let dateNow = NSDate() | |
let content = "\(dateFormatter.stringFromDate(dateNow)): - \(str)\n" | |
guard let data = content.dataUsingEncoding(NSUTF8StringEncoding) else { return } | |
if NSFileManager.defaultManager().fileExistsAtPath(filePath) { | |
do { | |
let fileHandler = try NSFileHandle.init(forWritingToURL: fileUrl) | |
fileHandler.seekToEndOfFile() | |
fileHandler.writeData(data) | |
fileHandler.closeFile() | |
} catch { | |
print("could not write to file: \(error)") | |
} | |
} else { | |
do { | |
try content.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding) | |
} catch let error as NSError { | |
print("Could not create to file: \(error.localizedDescription)") | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment