commit 867d39ba17f4c607b3bef5585bb474dfb66a4251
parent d65dee9a913e7c99acfe6049b66b63c9231c0aea
Author: Michael Camilleri <[email protected]>
Date: Mon, 19 Oct 2026 10:16:40 +0900
Add an event log for diagnosing background captures
Instant Reports are not saving location or weather when filed from
notifications sent to the Apple Watch. The cause is unknown and there is
no log that would indicate what is happening.
This commit adds an event log that keeps a day of entries in a file in
Application Support and copies each to the unified log. Settings gains
a Diagnostics section whose Event Log lists the entries, newest first,
with Share and Clear. Each entry is written to the file at once, since
the app can be suspended as soon as a background action returns, and
the file stays readable while the phone is locked, as it is when a
notification action runs.
The log records launches in the background, notification actions as
they arrive and are handled, the start and end of each capture with
which sections were captured, and weather errors. A capture that ends
without a fix says why: authorisation, no updates from Core Location,
or the diagnostic flags of the last update. Entries say what happened,
never what was recorded, so no coordinates, addresses or weather go in
the log.
Captures for notification actions now get 25 seconds rather than the
foreground's 10, as the design calls for, leaving a fix that starts
cold more time to arrive.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Reportage.xcodeproj/project.pbxproj | | | 20 | ++++++++++++++++++++ |
| M | Reportage/AppDelegate.swift | | | 12 | +++++++++--- |
| M | Reportage/Services/Prompts/PromptNotification.swift | | | 2 | +- |
| A | Reportage/Views/Settings/DiagnosticsSection.swift | | | 90 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Reportage/Views/Settings/SettingsView.swift | | | 1 | + |
| M | Shared/Capture/AppleWeather.swift | | | 5 | ++--- |
| M | Shared/Capture/ContextCapture.swift | | | 75 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- |
| A | Shared/Diagnostics/EventLog.swift | | | 147 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | Tests/Unit/EventLogTests.swift | | | 72 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
9 files changed, 413 insertions(+), 11 deletions(-)
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -11,6 +11,8 @@
047D3797389624E8B4AF44B4 /* ReportageExporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD433A98973E8B13E42230A1 /* ReportageExporter.swift */; };
06415D2A2EDA6E92ECAC96FA /* Report.swift in Sources */ = {isa = PBXBuildFile; fileRef = B03734F91822E7F161432075 /* Report.swift */; };
0F052B8A2C73437F57E927E7 /* ReportStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E55C093BA98D8700F406AE /* ReportStoreTests.swift */; };
+ 123470F9E3205890526D3A89 /* EventLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFF717BC324925C231BD3378 /* EventLog.swift */; };
+ 16CDDFE25EBB07C0EA9AC5AA /* DiagnosticsSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87545A7909A370C668314DFF /* DiagnosticsSection.swift */; };
16D2FB106A2C588BAAB3EB06 /* PromptSchedulerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2425CB4D9B12D422467F6FD7 /* PromptSchedulerTests.swift */; };
22EA393B887791E20B6FE625 /* PlacePickerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */; };
25BC9F95DC40E31B1E4C6FBA /* Token.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3BE62142CCC4A791F05163A /* Token.swift */; };
@@ -47,6 +49,7 @@
9EF3CB3707CD6B5AFFD3B767 /* ReporterArchive.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1C5F0F722477CDA949F018 /* ReporterArchive.swift */; };
A1FBFB9809DD3FF52BD7E5A7 /* DataSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA2E66BAB2463FD51EFE9F52 /* DataSection.swift */; };
A740B635075EB81AA70ED815 /* ReportDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F498961A14F24AE6CC37453C /* ReportDetailView.swift */; };
+ A7C988B20CD1C937A2E776D0 /* EventLogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7DD8E44D1A1F7789F528BD3 /* EventLogTests.swift */; };
B00AC94E13BC9C602179953E /* SurveyModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E382405EE9DBEC8EE616C1D /* SurveyModelTests.swift */; };
B454D3067CD611AE55E30A1D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 633FE6CD8111A433CA9BE7EC /* AppDelegate.swift */; };
B510BB2C1C11D72DFE15E3C7 /* ReportageExportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */; };
@@ -130,6 +133,7 @@
844ABAD88442C143BA239374 /* SurveyModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurveyModel.swift; sourceTree = "<group>"; };
84E55C093BA98D8700F406AE /* ReportStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportStoreTests.swift; sourceTree = "<group>"; };
86474CD2E8EC300CD6B37BB2 /* PromptSchedule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptSchedule.swift; sourceTree = "<group>"; };
+ 87545A7909A370C668314DFF /* DiagnosticsSection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiagnosticsSection.swift; sourceTree = "<group>"; };
878CE0FF7A2598F4197E8E61 /* Environment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Environment.swift; sourceTree = "<group>"; };
8E609FFCB918B4EF9BFCC018 /* DisplayRule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DisplayRule.swift; sourceTree = "<group>"; };
917C4579342FAC42F6C616FC /* ReporterImporterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImporterTests.swift; sourceTree = "<group>"; };
@@ -141,6 +145,7 @@
A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContextCaptureTests.swift; sourceTree = "<group>"; };
A3BE62142CCC4A791F05163A /* Token.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Token.swift; sourceTree = "<group>"; };
A70B6E5B7C07D2CE13E9E771 /* RootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootView.swift; sourceTree = "<group>"; };
+ A7DD8E44D1A1F7789F528BD3 /* EventLogTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventLogTests.swift; sourceTree = "<group>"; };
A9C326FBA3249ED86912FBF5 /* PromptNotification.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptNotification.swift; sourceTree = "<group>"; };
AF426915E941538164D91B18 /* NarrativePolisher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NarrativePolisher.swift; sourceTree = "<group>"; };
B007E6BACAA214C7332EF77C /* Question.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Question.swift; sourceTree = "<group>"; };
@@ -150,6 +155,7 @@
BC27A2AF600780976CFA295C /* PromptScheduleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptScheduleTests.swift; sourceTree = "<group>"; };
BEB5080BDA34F703DDC08ADB /* ReportDetailsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportDetailsTests.swift; sourceTree = "<group>"; };
BF998798373C9CCAD65999B3 /* TokenAnswer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TokenAnswer.swift; sourceTree = "<group>"; };
+ BFF717BC324925C231BD3378 /* EventLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventLog.swift; sourceTree = "<group>"; };
C17F34F71E3E13AF890DA2F3 /* Reportage.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Reportage.entitlements; sourceTree = "<group>"; };
C269C1BE83C1A5E08AC087E3 /* ReportDetails.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportDetails.swift; sourceTree = "<group>"; };
C3C7B68925A281EF806BB9B8 /* Theme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Theme.swift; sourceTree = "<group>"; };
@@ -288,6 +294,7 @@
isa = PBXGroup;
children = (
507C6AD120A3E0F91316F4B6 /* Capture */,
+ E8F9E24C79DBD151637A6A00 /* Diagnostics */,
4EF63181707B888F4ECDB980 /* Models */,
B9570B011A58C1B1BF00FB73 /* Persistence */,
);
@@ -298,6 +305,7 @@
isa = PBXGroup;
children = (
A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */,
+ A7DD8E44D1A1F7789F528BD3 /* EventLogTests.swift */,
D4AFF3D49ED9E8AC69390925 /* JSONSlicerTests.swift */,
5C606A9B0EF8D84950B9681B /* ModelCodingTests.swift */,
1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */,
@@ -362,6 +370,7 @@
isa = PBXGroup;
children = (
CA2E66BAB2463FD51EFE9F52 /* DataSection.swift */,
+ 87545A7909A370C668314DFF /* DiagnosticsSection.swift */,
81BA515BEA1B0B68CE0D1326 /* SettingsView.swift */,
);
path = Settings;
@@ -403,6 +412,14 @@
path = Generated;
sourceTree = "<group>";
};
+ E8F9E24C79DBD151637A6A00 /* Diagnostics */ = {
+ isa = PBXGroup;
+ children = (
+ BFF717BC324925C231BD3378 /* EventLog.swift */,
+ );
+ path = Diagnostics;
+ sourceTree = "<group>";
+ };
F7B8E02FFC282DCD163E25FE /* ReporterImport */ = {
isa = PBXGroup;
children = (
@@ -511,6 +528,7 @@
buildActionMask = 2147483647;
files = (
CFB0A1F9494F1D8919F48CC5 /* ContextCaptureTests.swift in Sources */,
+ A7C988B20CD1C937A2E776D0 /* EventLogTests.swift in Sources */,
8ADBA81D5D9ECCDCD5BDA742 /* JSONSlicerTests.swift in Sources */,
964408E4D25713F627048C77 /* ModelCodingTests.swift in Sources */,
22EA393B887791E20B6FE625 /* PlacePickerTests.swift in Sources */,
@@ -540,10 +558,12 @@
D487802C53EA0E96698BE151 /* ContextCapture.swift in Sources */,
A1FBFB9809DD3FF52BD7E5A7 /* DataSection.swift in Sources */,
BD8D81CBF8C3DE544BB7540C /* DefaultQuestions.swift in Sources */,
+ 16CDDFE25EBB07C0EA9AC5AA /* DiagnosticsSection.swift in Sources */,
D0497C9835A2502936591DC1 /* DisplayRule.swift in Sources */,
406D536D7764B3FEB140CAA0 /* EntityMapping.swift in Sources */,
770B4C77FABB2A7A0B2C5E3A /* EntryDraft.swift in Sources */,
C71E99843CC3D9DE4468B36B /* Environment.swift in Sources */,
+ 123470F9E3205890526D3A89 /* EventLog.swift in Sources */,
83E954F0DAC9719D2AA02111 /* HomeView.swift in Sources */,
6E21E729F89178EBD019980E /* InlineCasing.swift in Sources */,
3244B8439B5E4F79FF84C156 /* JSONSlicer.swift in Sources */,
diff --git a/Reportage/AppDelegate.swift b/Reportage/AppDelegate.swift
@@ -1,5 +1,4 @@
import BackgroundTasks
-import OSLog
import SwiftUI
import UserNotifications
@@ -9,12 +8,16 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCent
let persistence = PersistenceController()
let inbox = PromptInbox()
- private let logger = Logger(subsystem: "net.inqk.reportage", category: "Prompts")
+ private let log = EventLog.shared.category("Prompts")
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
+ // Says whether the app was opened or launched unseen, as it is for a
+ // notification action.
+ let state = application.applicationState == .background ? "in the background" : "in the foreground"
+ EventLog.shared.note("Launched \(state)", category: "App")
let center = UNUserNotificationCenter.current()
center.delegate = self
center.setNotificationCategories(PromptNotification.categories)
@@ -36,14 +39,17 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCent
private func handle(_ response: PromptResponse) async {
let store = ReportStore(persistence: persistence)
+ let state = UIApplication.shared.applicationState == .background ? "in the background" : "in the foreground"
+ log.info("Received '\(response.action)' for a '\(response.category)' notification, \(state)")
do {
let survey = try await PromptResponder(store: store)
.respond(to: response, settings: .load())
if let survey {
inbox.survey = survey
}
+ log.info("Handled '\(response.action)'")
} catch {
- logger.error("Couldn't respond to a prompt: \(error)")
+ log.error("Couldn't respond to a prompt: \(error)")
}
// An action is a chance to top up the prompts.
await AppBadge.update(from: store)
diff --git a/Reportage/Services/Prompts/PromptNotification.swift b/Reportage/Services/Prompts/PromptNotification.swift
@@ -127,7 +127,7 @@ struct PromptResponse: Sendable {
struct PromptResponder: Sendable {
let store: ReportStore
var center: any NotificationScheduling = SystemNotifications()
- var capture: @Sendable () async -> Context = { await ContextCapture().capture() }
+ var capture: @Sendable () async -> Context = { await ContextCapture.background.capture() }
/// Logs or snoozes the prompt, and returns the survey to open when the
/// notification itself was tapped.
diff --git a/Reportage/Views/Settings/DiagnosticsSection.swift b/Reportage/Views/Settings/DiagnosticsSection.swift
@@ -0,0 +1,90 @@
+import SwiftUI
+
+/// The event log: what the app did when no one was looking, for working out
+/// why something went wrong.
+struct DiagnosticsSection: View {
+ var body: some View {
+ Section {
+ NavigationLink("Event Log") { EventLogView() }
+ .settingsRow()
+ SettingsNote {
+ Text(
+ "A day of notes on what Reportage did in the background, such as logging an instant report. They say what happened, not what was recorded."
+ )
+ }
+ } header: {
+ SettingsHeading("Diagnostics")
+ }
+ }
+}
+
+/// The last day of the event log, newest first, to read or share.
+private struct EventLogView: View {
+ @State private var entries: [EventLog.Entry] = []
+ @State private var isConfirmingClear = false
+
+ var body: some View {
+ List {
+ if entries.isEmpty {
+ SettingsNote { Text("Nothing logged in the last day.") }
+ }
+ ForEach(entries.reversed()) { entry in
+ EventLogRow(entry: entry)
+ .settingsRow()
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .background(Theme.paper)
+ .foregroundStyle(Theme.ink)
+ .navigationTitle("Event Log")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItemGroup(placement: .primaryAction) {
+ ShareLink(item: EventLog.shared.text()) {
+ Label("Share", systemImage: "square.and.arrow.up")
+ }
+ .disabled(entries.isEmpty)
+ Button("Clear", systemImage: "trash") { isConfirmingClear = true }
+ .disabled(entries.isEmpty)
+ }
+ }
+ .confirmationDialog("Clear the Event Log?", isPresented: $isConfirmingClear, titleVisibility: .visible) {
+ Button("Clear", role: .destructive) {
+ EventLog.shared.clear()
+ load()
+ }
+ }
+ .refreshable { load() }
+ .onAppear { load() }
+ }
+
+ private func load() {
+ entries = EventLog.shared.all()
+ }
+}
+
+/// One entry: when, from which part of the app, and what happened.
+struct EventLogRow: View {
+ let entry: EventLog.Entry
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 2) {
+ HStack {
+ Text(entry.date, format: .dateTime.weekday(.abbreviated).hour().minute().second())
+ .monospacedDigit()
+ Text(verbatim: entry.category)
+ Spacer()
+ if entry.level != .info {
+ Text(verbatim: entry.level.rawValue)
+ .foregroundStyle(entry.level == .error ? Color.red : Theme.accent)
+ }
+ }
+ .font(.caption)
+ .foregroundStyle(Theme.muted)
+ Text(verbatim: entry.message)
+ .font(.footnote)
+ .textSelection(.enabled)
+ }
+ }
+}
diff --git a/Reportage/Views/Settings/SettingsView.swift b/Reportage/Views/Settings/SettingsView.swift
@@ -77,6 +77,7 @@ struct SettingsView: View {
}
}
DataSection()
+ DiagnosticsSection()
#if DEBUG
ScheduledPrompts(generation: scheduleGeneration)
#endif
diff --git a/Shared/Capture/AppleWeather.swift b/Shared/Capture/AppleWeather.swift
@@ -1,11 +1,10 @@
import CoreLocation
import Foundation
-import OSLog
import WeatherKit
/// Current conditions from WeatherKit, for a report's live context.
enum AppleWeather {
- private static let logger = Logger(subsystem: "net.inqk.reportage", category: "Weather")
+ private static let log = EventLog.shared.category("Weather")
/// The weather at `location` now, or `nil` if WeatherKit can't say.
/// Failures are logged: a missing entitlement or a service not yet
@@ -15,7 +14,7 @@ enum AppleWeather {
let current = try await WeatherService.shared.weather(for: location, including: .current)
return WeatherContext(current)
} catch {
- logger.error("Couldn't get the weather: \(error)")
+ log.error("Couldn't get the weather: \(error)")
return nil
}
}
diff --git a/Shared/Capture/ContextCapture.swift b/Shared/Capture/ContextCapture.swift
@@ -2,6 +2,7 @@ import CoreLocation
import Foundation
import MapKit
import Network
+import OSLog
#if os(iOS)
import UIKit
@@ -14,6 +15,15 @@ import Network
/// that fails, is denied or runs out of time leaves its section `nil`; none
/// of them can stop the report being saved.
struct ContextCapture: Sendable {
+ private static let log = EventLog.shared.category("Capture")
+ /// Details kept out of the event log, which is shared as it is.
+ private static let logger = Logger(subsystem: "net.inqk.reportage", category: "Capture")
+
+ /// A capture for a notification action, which runs in the background.
+ /// iOS gives an action about 30 seconds, and a fix there may start
+ /// cold, so it gets longer than the foreground's 10.
+ static let background = ContextCapture(budget: .seconds(25))
+
/// The whole capture's budget.
var budget: Duration = .seconds(10)
/// A fix at least this accurate, in metres, ends the search early.
@@ -32,13 +42,29 @@ struct ContextCapture: Sendable {
) async -> Context {
// The weather needs the fix, so the location capture hands it over
// as soon as it has one, and the two lookups run side by side.
+ Self.log.info("Started capturing, within \(budget.formatted(.units(allowed: [.seconds])))")
+ let start = ContinuousClock.now
let (fixes, handOver) = AsyncStream.makeStream(of: CLLocation.self)
async let location = captureLocation(onFix: { handOver.yield($0) }, onLocation: onLocation)
async let weather = captureWeather(from: fixes)
async let device = captureDevice()
let captured = await location
handOver.finish()
- return Context(location: captured, weather: await weather, device: await device)
+ let context = Context(location: captured, weather: await weather, device: await device)
+ let elapsed = start.duration(to: .now).formatted(.units(allowed: [.seconds], fractionalPart: .show(length: 1)))
+ Self.log.info(
+ """
+ Finished capturing after \(elapsed): location \(Self.found(context.location)), \
+ address \(Self.found(context.location?.placemark)), weather \(Self.found(context.weather)), \
+ device \(Self.found(context.device))
+ """)
+ return context
+ }
+
+ /// Whether a section was captured, for the event log, which never says
+ /// what it holds.
+ private static func found(_ section: (some Any)?) -> String {
+ section == nil ? "missing" : "captured"
}
// MARK: Weather
@@ -64,6 +90,8 @@ struct ContextCapture: Sendable {
defer { session.invalidate() }
guard await Self.isAuthorised(session) else { return nil }
guard let fix = await bestFix(within: budget - geocodingAllowance) else { return nil }
+ Self.logger.debug("Got a fix within \(fix.horizontalAccuracy)m")
+ Self.log.info("Got a fix")
var context = LocationContext(fix)
onFix(fix)
onLocation(context)
@@ -81,9 +109,12 @@ struct ContextCapture: Sendable {
/// showing, and reports whether location may be used. Gives up after a
/// minute so a prompt left on screen can't hold up saving forever.
private static func isAuthorised(_ session: CLServiceSession) async -> Bool {
- switch CLLocationManager().authorizationStatus {
+ let status = CLLocationManager().authorizationStatus
+ switch status {
case .authorizedWhenInUse, .authorizedAlways: return true
- case .denied, .restricted: return false
+ case .denied, .restricted:
+ log.notice("Location isn't authorised (status \(status.rawValue))")
+ return false
case .notDetermined: break
@unknown default: break
}
@@ -97,6 +128,9 @@ struct ContextCapture: Sendable {
} catch {}
return nil
}
+ if answer != true {
+ log.notice("Location wasn't authorised when asked")
+ }
return answer ?? false
}
@@ -106,8 +140,12 @@ struct ContextCapture: Sendable {
await withTaskGroup(of: CLLocation??.self) { group in
group.addTask {
var best: CLLocation?
+ var updates = 0
+ var last: CLLocationUpdate?
do {
for try await update in CLLocationUpdate.liveUpdates() {
+ updates += 1
+ last = update
if update.authorizationDenied || update.authorizationDeniedGlobally
|| update.authorizationRestricted
{
@@ -121,7 +159,12 @@ struct ContextCapture: Sendable {
if let best, best.horizontalAccuracy <= goodAccuracy { break }
if Task.isCancelled { break }
}
- } catch {}
+ } catch {
+ Self.log.error("Location updates failed: \(error)")
+ }
+ if best == nil {
+ Self.logUnfixed(updates: updates, last: last)
+ }
return .some(best)
}
group.addTask {
@@ -143,6 +186,30 @@ struct ContextCapture: Sendable {
}
}
+ /// Records why a search ended without a fix: the last update's
+ /// diagnostics say whether Core Location held updates back.
+ private static func logUnfixed(updates: Int, last: CLLocationUpdate?) {
+ guard let last else {
+ log.notice("No fix: no location updates arrived")
+ return
+ }
+ let flags = [
+ ("authorizationDenied", last.authorizationDenied),
+ ("authorizationDeniedGlobally", last.authorizationDeniedGlobally),
+ ("authorizationRestricted", last.authorizationRestricted),
+ ("authorizationRequestInProgress", last.authorizationRequestInProgress),
+ ("insufficientlyInUse", last.insufficientlyInUse),
+ ("serviceSessionRequired", last.serviceSessionRequired),
+ ("locationUnavailable", last.locationUnavailable),
+ ("accuracyLimited", last.accuracyLimited),
+ ("stationary", last.stationary),
+ ]
+ let set = flags.filter(\.1).map(\.0).joined(separator: ", ")
+ log.notice(
+ "No fix after \(updates) updates; last had location: \(last.location != nil), flags: \(set.isEmpty ? "none" : set)"
+ )
+ }
+
/// The fix's address in the user's first language and, where the
/// place's own language differs, in that language too. Together they let
/// an address be shown in the local language when the user knows it,
diff --git a/Shared/Diagnostics/EventLog.swift b/Shared/Diagnostics/EventLog.swift
@@ -0,0 +1,147 @@
+import Foundation
+import OSLog
+import Synchronization
+
+/// Breadcrumbs kept on the device, so what happened while the app ran
+/// unseen, such as an Instant Report from the Watch, can be read later in
+/// Settings or shared from there.
+///
+/// Each entry is also sent to the unified log, so it streams in Console.app
+/// when the phone is connected. The file is the record: the system log
+/// redacts and drops what a tethered session doesn't catch.
+///
+/// Messages are read and shared as they are, so they say what happened and
+/// why, never what was recorded: no coordinates, addresses, answers or
+/// weather.
+final class EventLog: Sendable {
+ static let shared = EventLog()
+
+ struct Entry: Codable, Identifiable, Equatable, Sendable {
+ var id = UUID()
+ let date: Date
+ let level: Level
+ let category: String
+ let message: String
+ }
+
+ enum Level: String, Codable, Sendable {
+ case info
+ case notice
+ case error
+ }
+
+ /// How far back the log reaches: a day spans a day out with the phone
+ /// and the evening it's read in.
+ let retention: TimeInterval
+ /// A ceiling in case something logs in a loop. Ordinary use writes a
+ /// few dozen entries a day, so the retention is what governs.
+ let maxEntries: Int
+
+ private let fileURL: URL?
+ /// Loaded from the file on first use.
+ private let entries = Mutex<[Entry]?>(nil)
+
+ init(
+ fileURL: URL? = EventLog.defaultURL,
+ retention: TimeInterval = 24 * 60 * 60,
+ maxEntries: Int = 5_000
+ ) {
+ self.fileURL = fileURL
+ self.retention = retention
+ self.maxEntries = maxEntries
+ }
+
+ /// In Application Support rather than Caches, which iOS can empty just
+ /// when the log is wanted.
+ static var defaultURL: URL? {
+ try? FileManager.default
+ .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
+ .appending(path: "event-log.json")
+ }
+
+ /// A logger for one part of the app, used like `Logger`.
+ func category(_ name: String) -> Category {
+ Category(name: name, log: self)
+ }
+
+ /// Adds an entry and writes the file at once. The app can be suspended
+ /// as soon as a background action returns, so nothing waits for later.
+ func note(_ message: String, level: Level = .info, category: String, now: Date = Date()) {
+ let logger = Logger(subsystem: "net.inqk.reportage", category: category)
+ switch level {
+ case .info: logger.info("\(message, privacy: .public)")
+ case .notice: logger.notice("\(message, privacy: .public)")
+ case .error: logger.error("\(message, privacy: .public)")
+ }
+ entries.withLock { entries in
+ var current = entries ?? load()
+ current.append(Entry(date: now, level: level, category: category, message: message))
+ prune(¤t, now: now)
+ entries = current
+ save(current)
+ }
+ }
+
+ /// Every entry within the retention, oldest first.
+ func all(now: Date = Date()) -> [Entry] {
+ entries.withLock { entries in
+ var current = entries ?? load()
+ prune(¤t, now: now)
+ entries = current
+ return current
+ }
+ }
+
+ func clear() {
+ entries.withLock { entries in
+ entries = []
+ save([])
+ }
+ }
+
+ /// The log as plain text, oldest first, for sharing.
+ func text(now: Date = Date()) -> String {
+ // Local time with its offset, as the times in the timeline are.
+ let style = Date.ISO8601FormatStyle(includingFractionalSeconds: true, timeZone: .current)
+ return all(now: now)
+ .map { "\($0.date.formatted(style)) [\($0.category)] \($0.level.rawValue): \($0.message)" }
+ .joined(separator: "\n")
+ }
+
+ private func load() -> [Entry] {
+ guard let fileURL, let data = try? Data(contentsOf: fileURL) else { return [] }
+ return (try? JSONDecoder().decode([Entry].self, from: data)) ?? []
+ }
+
+ private func save(_ entries: [Entry]) {
+ guard let fileURL, let data = try? JSONEncoder().encode(entries) else { return }
+ // Readable while the phone is locked, as it is when a notification
+ // action runs.
+ try? data.write(to: fileURL, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
+ }
+
+ /// Entries are in date order, so the expired ones are a prefix.
+ private func prune(_ entries: inout [Entry], now: Date) {
+ let cutoff = now.addingTimeInterval(-retention)
+ if let fresh = entries.firstIndex(where: { $0.date >= cutoff }) {
+ entries.removeFirst(fresh)
+ } else {
+ entries.removeAll()
+ }
+ if entries.count > maxEntries {
+ entries.removeFirst(entries.count - maxEntries)
+ }
+ }
+}
+
+extension EventLog {
+ /// One part of the app's entries.
+ struct Category: Sendable {
+ let name: String
+ let log: EventLog
+
+ func info(_ message: String) { log.note(message, level: .info, category: name) }
+ func notice(_ message: String) { log.note(message, level: .notice, category: name) }
+ func error(_ message: String) { log.note(message, level: .error, category: name) }
+ }
+}
diff --git a/Tests/Unit/EventLogTests.swift b/Tests/Unit/EventLogTests.swift
@@ -0,0 +1,72 @@
+import Foundation
+import Testing
+
+@testable import Reportage
+
+@Suite("EventLog")
+struct EventLogTests {
+ private func makeURL() -> URL {
+ URL.temporaryDirectory.appending(path: "event-log-\(UUID().uuidString).json")
+ }
+
+ @Test("Entries are written at once, so a new log on the same file reads them")
+ func persists() {
+ let url = makeURL()
+ defer { try? FileManager.default.removeItem(at: url) }
+ let now = Date()
+ EventLog(fileURL: url).note("Launched", category: "App", now: now)
+ EventLog(fileURL: url).note("No fix", level: .notice, category: "Capture", now: now.addingTimeInterval(1))
+
+ let entries = EventLog(fileURL: url).all(now: now.addingTimeInterval(2))
+ #expect(entries.map(\.message) == ["Launched", "No fix"])
+ #expect(entries.map(\.level) == [.info, .notice])
+ #expect(entries.map(\.category) == ["App", "Capture"])
+ }
+
+ @Test("Entries older than the retention are dropped")
+ func retention() {
+ let log = EventLog(fileURL: nil, retention: 60)
+ let start = Date()
+ log.note("Old", category: "App", now: start)
+ log.note("New", category: "App", now: start.addingTimeInterval(50))
+
+ #expect(log.all(now: start.addingTimeInterval(55)).map(\.message) == ["Old", "New"])
+ #expect(log.all(now: start.addingTimeInterval(70)).map(\.message) == ["New"])
+ #expect(log.all(now: start.addingTimeInterval(200)).isEmpty)
+ }
+
+ @Test("Only the newest entries are kept past the ceiling")
+ func ceiling() {
+ let log = EventLog(fileURL: nil, maxEntries: 3)
+ let now = Date()
+ for i in 1...5 {
+ log.note("\(i)", category: "App", now: now.addingTimeInterval(Double(i)))
+ }
+ #expect(log.all(now: now.addingTimeInterval(6)).map(\.message) == ["3", "4", "5"])
+ }
+
+ @Test("Clearing empties the file too")
+ func clear() {
+ let url = makeURL()
+ defer { try? FileManager.default.removeItem(at: url) }
+ let log = EventLog(fileURL: url)
+ log.note("Launched", category: "App")
+ log.clear()
+
+ #expect(log.all().isEmpty)
+ #expect(EventLog(fileURL: url).all().isEmpty)
+ }
+
+ @Test("The shared text has one line per entry, with its category and level")
+ func text() {
+ let log = EventLog(fileURL: nil)
+ let now = Date()
+ log.note("Launched", category: "App", now: now)
+ log.note("Couldn't get the weather", level: .error, category: "Weather", now: now)
+
+ let lines = log.text(now: now).split(separator: "\n")
+ #expect(lines.count == 2)
+ #expect(lines[0].hasSuffix("[App] info: Launched"))
+ #expect(lines[1].hasSuffix("[Weather] error: Couldn't get the weather"))
+ }
+}