Cotton code
121 lines · 4.8 KB · SwiftRaw
import Foundationimport os/// The app's log: one call, two readers.////// **A line goes to Console AND into a ring the next report carries.** The/// phone had no log at all before this — four `print`s, which a device in a/// pocket never shows anyone — and a report that arrived as one sentence with/// nothing before it. Now every line is written once, here, and:////// - `os.Logger` gets it, so a developer with the phone on a cable reads it in///   Console.app under the app's own subsystem, and/// - `LogRing` keeps the last `LogRing.defaultCapacity` of them in memory, and///   `Reporting.report` drains the ring into every report it sends, scrubbed by///   the same `Reporting.scrub` as the message (`Reporting.swift`).////// **The lines are public in the `os.Logger` sense on purpose.** The default/// redacts every interpolated value, which is right for a line that might carry/// a person's text and wrong for these: a log line here is about the SOFTWARE —/// a route, a method name, a refusal code, a count — never about the owner./// That is the same rule `Report` states about its own context, and for the/// same reason: what leaves this phone is read by whoever runs Bugsink.////// Not `Cotton.log`: the app target's module is named `Cotton`, so a type of/// that name in this library is unreachable from the app's own sources/// without qualifying it on every call.public enum Log {    /// The one ring every report drains. Sized once, here.    public static let ring = LogRing(capacity: LogRing.defaultCapacity)    /// The subsystem is this flavor's app id, so Console tells the two apps'    /// lines apart.    private static let logger = Logger(subsystem: AppFlavor.current.phoneAppID, category: "cotton")    /// Write one line. Cheap enough to call from anywhere, on any thread.    public static func write(_ line: String) {        ring.append(line)        logger.log("\(line, privacy: .public)")    }    /// Write one line at WARNING level — something the software got wrong that    /// it then carried on from.    ///    /// The ring keeps it exactly as `write` does, because a report wants the    /// same sequence either way; what differs is Console's own level, which is    /// how a developer filters a hundred ordinary lines down to the one that    /// says a URL did not parse. `warning` is `os.Logger`'s level for "an    /// error was handled" — it persists to the log store, where `log` may not.    public static func warn(_ line: String) {        ring.append(line)        logger.warning("\(line, privacy: .public)")    }}/// One line the ring holds: when, and what.public struct LogLine: Sendable, Equatable {    public let at: Date    public let text: String    public init(at: Date, text: String) {        self.at = at        self.text = text    }}/// The last N lines, in memory, on any thread.////// A ring rather than a file: a report is the only reader, it wants the recent/// past and nothing older, and a file the app appends to for ever is a file/// somebody has to rotate. Two hundred lines is enough to see how a screen was/// reached and what the core answered on the way.public final class LogRing: @unchecked Sendable {    /// What `Log.ring` is sized to. Lane J's brief named the number.    /// 500, so a phone report (`diagnostics.report`) carries the last 500 lines.    public static let defaultCapacity = 500    public let capacity: Int    private let lock = NSLock()    private var held: [LogLine] = []    private let clock: @Sendable () -> Date    public init(capacity: Int, clock: @escaping @Sendable () -> Date = { Date() }) {        precondition(capacity > 0, "a ring holds at least one line")        self.capacity = capacity        self.clock = clock    }    public func append(_ text: String) {        let line = LogLine(at: clock(), text: text)        lock.lock()        defer { lock.unlock() }        held.append(line)        if held.count > capacity {            held.removeFirst(held.count - capacity)        }    }    /// Oldest first.    public func lines() -> [LogLine] {        lock.lock()        defer { lock.unlock() }        return held    }    /// The lines as a report carries them: `HH:mm:ss.SSS text`, UTC, oldest    /// first. UTC because a Bugsink event's own clock is UTC and a reader    /// lining the two up should not have to know the phone's zone.    public func rendered() -> [String] {        let formatter = DateFormatter()        formatter.locale = Locale(identifier: "en_US_POSIX")        formatter.timeZone = TimeZone(identifier: "UTC")        formatter.dateFormat = "HH:mm:ss.SSS"        return lines().map { "\(formatter.string(from: $0.at)) \($0.text)" }    }    public func clear() {        lock.lock()        defer { lock.unlock() }        held.removeAll()    }}