Created
April 29, 2022 21:22
-
-
Save Megatron1000/b5e9a8beda6b9866f9c50c3baad338d6 to your computer and use it in GitHub Desktop.
Export OSLog To File
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 OSLog | |
@available(iOS 15.0, *) | |
final class LogReportCreator { | |
enum LogReportCreatorError: Error { | |
case noEntries | |
case unableToFindCachesDirectory | |
case unknownError(error: Error) | |
} | |
func generateLogFile(completion: @escaping ((Result<URL, LogReportCreatorError>) -> Void)) { | |
DispatchQueue.global(qos: .userInitiated).async { | |
do { | |
let store = try OSLogStore(scope: .currentProcessIdentifier) | |
let position = store.position(timeIntervalSinceEnd: -60.0*60.0*24) | |
let entries = try store.getEntries(with: [], at: position, matching: nil) | |
var logString = String() | |
for e in entries { | |
logString.append(contentsOf: e.date.ISO8601Format()) | |
logString.append(contentsOf: ": ") | |
logString.append(contentsOf: e.composedMessage) | |
logString.append(contentsOf: "\n") | |
} | |
guard logString.isEmpty == false else { | |
completion(.failure(.noEntries)) | |
return | |
} | |
guard let path = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else { | |
completion(.failure(.unableToFindCachesDirectory)) | |
return | |
} | |
let filename = path.appendingPathComponent("\(Date().ISO8601Format()).log") | |
try logString.write(to: filename, atomically: true, encoding: String.Encoding.utf8) | |
completion(.success(filename)) | |
} | |
catch { | |
completion(.failure(.unknownError(error: error))) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment