Skip to content

Instantly share code, notes, and snippets.

@vhart
Last active April 17, 2018 19:21
Show Gist options
  • Save vhart/23b516de3d767944c23147ed2f9ea9e8 to your computer and use it in GitHub Desktop.
Save vhart/23b516de3d767944c23147ed2f9ea9e8 to your computer and use it in GitHub Desktop.
Basic Logger - Swift 3 Version
/*
from console. `po NSHomeDirectory()`
from terminal cd to that path
cd into Documents
LogFile.txt should be there
To see content update live run tail -F LogFile.txt
*/
public class BasicLogger: NSObject {
private static let queue = DispatchQueue(label: "com.vhart.basicLoggerQueue")
private static let dateFormatter = DateFormatter()
fileprivate static var filePath: String {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask,
true)
let documentsDirectory = paths[0] as NSString
return documentsDirectory.appendingPathComponent("LogFile.txt")
}
class func write(file: String = #file,
function: String = #function,
line: Int = #line,
message: String) {
let fileName = (file as NSString).lastPathComponent
write("\(fileName) \(function): \(line): -- \(message)")
}
// 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"];
//
@objc public 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)")
}
fileprivate class func write(_ str: String) {
queue.async {
dateFormatter.dateFormat = "MM-dd-yyyy'| 'HH:mm:ss +SSS'|'"
let dateNow = Date()
let content = "\(dateFormatter.string(from: dateNow)): - \(str)\n"
if let fileUpdater = try? FileHandle(forUpdating: URL(fileURLWithPath: filePath)) {
fileUpdater.seekToEndOfFile()
fileUpdater.write(content.data(using: .utf8)!)
fileUpdater.closeFile()
} else {
do {
try content.write(toFile: filePath,
atomically: true,
encoding: .utf8)
} catch let error as NSError {
print("Could not append to file: \(error.localizedDescription)")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment