Last active
June 6, 2024 05:38
-
-
Save huynguyencong/76f48611f5973cf698e3f8843fa89ab5 to your computer and use it in GitHub Desktop.
Log to a file, then use `copyLogToClipboard()` or `printLog()` function to read it.
This file contains 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
import Foundation | |
import UIKit | |
class FileLogger { | |
private static let defaultFileName = "log.txt" | |
static let shared = FileLogger() | |
private init() { | |
read() | |
} | |
private var fileName: String = FileLogger.defaultFileName | |
private var shouldLogTime = true | |
private var shouldPrintLog = true | |
private(set) var content: String = "" | |
private var filePath: String? { | |
FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent(fileName).path | |
} | |
func changeConfiguration(fileName: String, shouldLogTime: Bool, shouldPrintLog: Bool) { | |
self.fileName = fileName | |
self.shouldLogTime = shouldLogTime | |
self.shouldPrintLog = shouldPrintLog | |
} | |
func log(_ message: String) { | |
let newMessage = "\(shouldLogTime ? "\(Date()): " : "")\(message)\n" | |
content += newMessage | |
write() | |
if shouldPrintLog { | |
print(newMessage) | |
} | |
} | |
private func read() { | |
guard let filePath else { | |
print("FileLogger - Read failed - Path not found") | |
return | |
} | |
do { | |
content = try String(contentsOfFile: filePath) | |
} catch { | |
print("FileLogger - Read failed - \(error.localizedDescription)") | |
} | |
} | |
private func write() { | |
guard let filePath else { | |
print("FileLogger - Write failed - Path not found") | |
return | |
} | |
do { | |
try content.write(toFile: filePath, atomically: true, encoding: .utf8) | |
} catch { | |
print("FileLogger - Write failed - \(error.localizedDescription)") | |
} | |
} | |
func copyLogToClipboard() { | |
UIPasteboard.general.string = content | |
print("FileLogger - Copied to clipboard") | |
} | |
func printLog() { | |
print(content) | |
} | |
func clear() { | |
content = "" | |
write() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment