Files
amnezia-client/client/platforms/ios/Log.swift
T

83 lines
1.9 KiB
Swift
Raw Normal View History

2024-02-10 19:44:55 +03:00
import Foundation
import os.log
struct Log {
private static let IsLoggingEnabledKey = "IsLoggingEnabled"
static var isLoggingEnabled: Bool {
get {
sharedUserDefaults.bool(forKey: IsLoggingEnabledKey)
}
set {
sharedUserDefaults.setValue(newValue, forKey: IsLoggingEnabledKey)
}
}
private static let appGroupID = "group.org.amnezia.AmneziaVPN"
2024-02-11 01:55:54 +03:00
2024-02-10 19:44:55 +03:00
static let neLogURL = {
let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupID)!
return sharedContainerURL.appendingPathComponent("ne.log", isDirectory: false)
}()
2024-02-11 01:55:54 +03:00
2024-02-10 19:44:55 +03:00
private static var sharedUserDefaults = {
UserDefaults(suiteName: appGroupID)!
}()
2024-02-11 01:55:54 +03:00
2024-02-10 19:44:55 +03:00
static let dateFormatter: DateFormatter = {
2024-02-11 01:55:54 +03:00
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter
2024-02-10 19:44:55 +03:00
}()
var records: [Record]
2024-02-11 01:55:54 +03:00
2024-02-10 19:44:55 +03:00
init() {
self.records = []
}
2024-02-11 01:55:54 +03:00
2024-02-10 19:44:55 +03:00
init(_ str: String) {
self.records = str.split(whereSeparator: \.isNewline)
.compactMap {
2024-02-12 19:16:41 +03:00
Record(String($0))
2024-02-10 19:44:55 +03:00
}
}
2024-02-11 01:55:54 +03:00
2024-02-10 19:44:55 +03:00
init?(at url: URL) {
if !FileManager.default.fileExists(atPath: url.path) {
2024-02-11 01:55:54 +03:00
guard (try? "".data(using: .utf8)?.write(to: url)) != nil else { return nil }
2024-02-10 19:44:55 +03:00
}
2024-02-11 01:55:54 +03:00
2024-02-10 19:44:55 +03:00
guard let fileHandle = try? FileHandle(forUpdating: url) else { return nil }
2024-02-11 01:55:54 +03:00
2024-02-10 19:44:55 +03:00
defer { fileHandle.closeFile() }
2024-02-11 01:55:54 +03:00
2024-02-10 19:44:55 +03:00
guard
let data = try? fileHandle.readToEnd(),
let str = String(data: data, encoding: .utf8) else {
return nil
}
2024-02-11 01:55:54 +03:00
2024-02-10 19:44:55 +03:00
self.init(str)
}
2024-02-11 01:55:54 +03:00
2024-02-10 19:44:55 +03:00
static func clear(at url: URL) {
if FileManager.default.fileExists(atPath: url.path) {
guard let fileHandle = try? FileHandle(forUpdating: url) else { return }
2024-02-11 01:55:54 +03:00
2024-02-10 19:44:55 +03:00
defer { fileHandle.closeFile() }
2024-02-11 01:55:54 +03:00
2024-02-10 19:44:55 +03:00
try? fileHandle.truncate(atOffset: 0)
}
}
}
extension Log: CustomStringConvertible {
var description: String {
records
.map {
$0.description
}
.joined(separator: "\n")
}
}