← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Shared/Diagnostics/EventLog.swift (5347B)

1import Foundation
2import OSLog
3import Synchronization
4
5/// Breadcrumbs kept on the device, so what happened while the app ran
6/// unseen, such as an Instant Report from the Watch, can be read later in
7/// Settings or shared from there.
8///
9/// Each entry is also sent to the unified log, so it streams in Console.app
10/// when the phone is connected. The file is the record: the system log
11/// redacts and drops what a tethered session doesn't catch.
12///
13/// Messages are read and shared as they are, so they say what happened and
14/// why, never what was recorded: no coordinates, addresses, answers or
15/// weather.
16final class EventLog: Sendable {
17    static let shared = EventLog()
18
19    struct Entry: Codable, Identifiable, Equatable, Sendable {
20        var id = UUID()
21        let date: Date
22        let level: Level
23        let category: String
24        let message: String
25    }
26
27    enum Level: String, Codable, Sendable {
28        case info
29        case notice
30        case error
31    }
32
33    /// How far back the log reaches: a day spans a day out with the phone
34    /// and the evening it's read in.
35    let retention: TimeInterval
36    /// A ceiling in case something logs in a loop. Ordinary use writes a
37    /// few dozen entries a day, so the retention is what governs.
38    let maxEntries: Int
39
40    private let fileURL: URL?
41    /// Loaded from the file on first use.
42    private let entries = Mutex<[Entry]?>(nil)
43
44    init(
45        fileURL: URL? = EventLog.defaultURL,
46        retention: TimeInterval = 24 * 60 * 60,
47        maxEntries: Int = 5_000
48    ) {
49        self.fileURL = fileURL
50        self.retention = retention
51        self.maxEntries = maxEntries
52    }
53
54    /// In Application Support rather than Caches, which iOS can empty just
55    /// when the log is wanted.
56    static var defaultURL: URL? {
57        try? FileManager.default
58            .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
59            .appending(path: "event-log.json")
60    }
61
62    /// A logger for one part of the app, used like `Logger`.
63    func category(_ name: String) -> Category {
64        Category(name: name, log: self)
65    }
66
67    /// Adds an entry and writes the file at once. The app can be suspended
68    /// as soon as a background action returns, so nothing waits for later.
69    func note(_ message: String, level: Level = .info, category: String, now: Date = Date()) {
70        let logger = Logger(subsystem: "net.inqk.reportage", category: category)
71        switch level {
72        case .info: logger.info("\(message, privacy: .public)")
73        case .notice: logger.notice("\(message, privacy: .public)")
74        case .error: logger.error("\(message, privacy: .public)")
75        }
76        entries.withLock { entries in
77            var current = entries ?? load()
78            current.append(Entry(date: now, level: level, category: category, message: message))
79            prune(&current, now: now)
80            entries = current
81            save(current)
82        }
83    }
84
85    /// Every entry within the retention, oldest first.
86    func all(now: Date = Date()) -> [Entry] {
87        entries.withLock { entries in
88            var current = entries ?? load()
89            prune(&current, now: now)
90            entries = current
91            return current
92        }
93    }
94
95    func clear() {
96        entries.withLock { entries in
97            entries = []
98            save([])
99        }
100    }
101
102    /// The log as plain text, oldest first, for sharing.
103    func text(now: Date = Date()) -> String {
104        // Local time with its offset, as the times in the timeline are.
105        let style = Date.ISO8601FormatStyle(includingFractionalSeconds: true, timeZone: .current)
106        return all(now: now)
107            .map { "\($0.date.formatted(style)) [\($0.category)] \($0.level.rawValue): \($0.message)" }
108            .joined(separator: "\n")
109    }
110
111    private func load() -> [Entry] {
112        guard let fileURL, let data = try? Data(contentsOf: fileURL) else { return [] }
113        return (try? JSONDecoder().decode([Entry].self, from: data)) ?? []
114    }
115
116    private func save(_ entries: [Entry]) {
117        guard let fileURL, let data = try? JSONEncoder().encode(entries) else { return }
118        // Readable while the phone is locked, as it is when a notification
119        // action runs.
120        try? data.write(to: fileURL, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
121    }
122
123    /// Entries are in date order, so the expired ones are a prefix.
124    private func prune(_ entries: inout [Entry], now: Date) {
125        let cutoff = now.addingTimeInterval(-retention)
126        if let fresh = entries.firstIndex(where: { $0.date >= cutoff }) {
127            entries.removeFirst(fresh)
128        } else {
129            entries.removeAll()
130        }
131        if entries.count > maxEntries {
132            entries.removeFirst(entries.count - maxEntries)
133        }
134    }
135}
136
137extension EventLog {
138    /// One part of the app's entries.
139    struct Category: Sendable {
140        let name: String
141        let log: EventLog
142
143        func info(_ message: String) { log.note(message, level: .info, category: name) }
144        func notice(_ message: String) { log.note(message, level: .notice, category: name) }
145        func error(_ message: String) { log.note(message, level: .error, category: name) }
146    }
147}