Swift
Structured logs from your iOS, macOS, tvOS, watchOS or visionOS app. No dependencies.
The Swift SDK needs iOS 16, macOS 13, tvOS 16, watchOS 9 or visionOS 1, and Swift 6. Some features depend on the platform: see Platforms.
Internal preview: this package isn't published yet. Until it is, Xcode can't fetch it: the repository is private and has no release yet.
Install
Swift Package Manager. In Xcode, choose File > Add Package Dependencies, enter
https://github.com/GonzaloFuentes28/lyrelog-swift and add the product Lyrelog to your app's
target. In Package.swift:
dependencies: [
.package(url: "https://github.com/GonzaloFuentes28/lyrelog-swift", from: "0.1.0"),
],
targets: [
.target(name: "MyApp", dependencies: [.product(name: "Lyrelog", package: "lyrelog-swift")]),
]Start
Start once, as early as possible, for example in your App's init. A second call is ignored.
Events logged before start are ignored too, but setUser and setConsent called before
start are kept and applied when it runs.
import Lyrelog
@main
struct MyApp: App {
init() {
Lyrelog.start(Configuration(
apiKey: "lyr_ing_..." // ingest-only: it can append events, never read them
))
}
var body: some Scene { WindowGroup { ContentView() } }
}Events go to https://ingest.lyrelog.com. Pass endpoint only to send them somewhere else. It
is the base URL (a pasted .../v1/events:batch path is stripped) and must be https; plain
http works only for localhost, 127.0.0.1 or ::1. With any other endpoint nothing is sent
and the events stay on the device.
Log events
One function per level: trace, debug, info, notice, warning, error, critical, or
log(_:_:) with a level.
Lyrelog.info("checkout_done", attrs: ["items": 3, "latency_ms": .int(ms)])
Lyrelog.error("payment_declined", category: "checkout",
attrs: ["code": 51], payload: ["response": .string(raw)])Attributes and payloads are LogValues. Literals work directly ("text", 412, 0.5, true,
["a", "b"], nested dictionaries, nil); for variables use the cases (.int(ms),
.string(name), .double(x), .bool(flag)) or LogValue(x). LogValue(duration) turns a
Duration into milliseconds.
If your app has its own LogLevel type, refer to Lyrelog's as Lyrelog.Level.
Loggers for each area
A logger stamps its category on every event, like OSLog's Logger(category:). It has every
level except trace, plus log and captureError.
let sync = Lyrelog.Logger(category: "sync")
sync.warning("sync_conflict", attrs: ["records": 2])Users
Lyrelog.setUser(playerID) // attached to every following event
Lyrelog.setUser(nil) // on sign-outLyrelog.sessionID gives the current session id, for example to show in a support screen.
The user id isn't saved between launches: call setUser again on each launch, once you know who
the person is.
Screens
Say where the person is. Lyrelog logs screen_viewed (area navigation) with the screen before
and the seconds spent on it, and tags every following event with a screen attribute.
Lyrelog.screen("Settings") // anywhere
SettingsView().lyrelogScreen("Settings") // or in SwiftUI, on appearThe event carries screen, previous_screen and seconds_on_previous. Calling screen again
with the same name logs nothing. Both forms take extra attrs for the screen_viewed event.
Turn the tagging off with attachScreen: false.
Network requests
Requests become http_request and http_request_failed events in the network area, with the
method, the host, a path whose ids are folded to :id, the status, the duration and the size.
Never the query string, the headers or the body.
let (data, response) = try await URLSession.shared.loggedData(for: request)If your paths carry things the folding can't recognize, pass the route yourself:
loggedData(for: request, route: "/players/:id/stats").
loggedData(for:route:category:) works on any URLSession. With your own client, record each request
yourself:
let clock = ContinuousClock()
let start = clock.now
let (data, response) = try await myClient.send(request)
Lyrelog.Network.record(request, response: response, error: nil, duration: clock.now - start, bytes: data.count, route: "/orders/:id")duration is a Swift Duration: measure it with ContinuousClock, as above.
bytes and category (default network) are optional. 2xx and 3xx are debug, 4xx warning,
5xx and failures error (a canceled request is debug). A failure carries error_domain and
error_code.
Errors you catch
do {
try await store.purchase(product)
} catch {
Lyrelog.captureError(error, category: "store")
}It sends the exception event every SDK sends: level error, the attributes error_type and
error_message, and a payload with the description, the NSError domain and code, and the
underlying error. attrs: adds your own; level: changes the level. Each Logger has
captureError too.
Crashes and hangs
Crashes and hangs come from MetricKit (iOS, macOS, visionOS), on by default
(captureDiagnostics). iOS hands them over on the next launch, so each one becomes an event at
the time it happened, without a session, in the diagnostics area:
| Event | Level | What it carries |
|---|---|---|
app_crashed | critical | Exception, signal, termination reason, the version and device it happened on, the top frame of your app, and up to 60 frames in the payload |
app_hung | error | How long it hung |
cpu_overuse | warning | |
disk_write_overuse | warning | |
slow_launch | warning |
A report delivered twice is stored once. Frames are offsets into each binary, not symbols:
symbolicate them with the dSYM when you need names. Each frame reads MyApp +0x1a2b3c: the
binary and the offset into its code, and the payload's binary_images gives each binary's UUID. With the
dSYM of the build that crashed (Xcode's Organizer, or your archive), atos turns an offset into
the function, file and line. Pass the binary's usual load address, 0x100000000 for an app on
arm64, and that address plus the offset:
atos -arch arm64 \
-o MyApp.app.dSYM/Contents/Resources/DWARF/MyApp \
-l 0x100000000 \
0x1001a2b3cCheck first that the dSYM's UUID (dwarfdump --uuid MyApp.app.dSYM) matches the one in
binary_images.
Environments and platform
When it starts, the SDK picks the environment:
developmentfor a Debug build, any build on the simulator, or a build with an embedded provisioning profile (development, ad hoc and enterprise signing);testflightfor a build with a sandbox App Store receipt and no profile;productionotherwise.
Then it asks StoreKit in the background (AppTransaction.shared.environment), without a prompt,
and events logged after it answers carry that answer: xcode is development, sandbox is
testflight, production is production. That's how a Mac app from TestFlight is told apart.
Offline or signed out, the first answer stays, and a Mac app counts as production until
StoreKit answers.
Your own runs from Xcode send development, while the dashboard opens on production: pick
development in the top bar to see them.
The platform is the OS (ios, macos, tvos, visionos; apple on watchOS). Override either
in the configuration:
Configuration(apiKey: key,
environment: isInternalTester ? "internal" : nil, // nil = detected
platform: nil)Lyrelog.detectedEnvironment is the answer at start; await Lyrelog.detectEnvironment() waits
for StoreKit too (up to 10 seconds). Any name works: lowercase letters, digits, - and _, up
to 32. Other text is turned into a valid name (Staging EU becomes staging-eu).
Platforms
| iOS, iPadOS, visionOS | tvOS | macOS | watchOS | |
|---|---|---|---|---|
platform | ios, visionos | tvos | macos | apple |
| Sends when the app goes to the background | Yes | Yes | No | No |
| Crashes and hangs (MetricKit) | Yes | No | Yes | No |
Without a background send, events are sent on the timer while the app runs, and what's left
goes out on the next launch, since the queue is on disk. On watchOS, os_name is unknown.
Consent
Lyrelog.start(Configuration(apiKey: key, consent: .pending))
// later, when the person chooses:
Lyrelog.setConsent(.granted) // sends, including what was kept while pending
Lyrelog.setConsent(.denied) // deletes everything and stops recording.pending keeps events on the device without sending them. Starting with consent: .denied
deletes anything still queued from an earlier launch and the install id, and records nothing.
Consent isn't saved between launches: store the person's choice yourself and pass it to
start each time.
A complete app
Start with the stored consent, set the person when they sign in and tag screens:
import Lyrelog
import SwiftUI
@main
struct MyApp: App {
init() {
let consent: Lyrelog.Consent = switch UserDefaults.standard.string(forKey: "diagnostics") {
case "granted": .granted
case "denied": .denied
default: .pending
}
Lyrelog.start(Configuration(apiKey: "lyr_ing_...", consent: consent))
}
var body: some Scene {
WindowGroup { RootView() }
}
}
struct RootView: View {
@State private var account: Account?
var body: some View {
Group {
if let account {
HomeView(account: account).lyrelogScreen("Home")
} else {
SignInView { signedIn in
account = signedIn
Lyrelog.setUser(signedIn.id)
Lyrelog.info("signed_in", category: "auth")
}
.lyrelogScreen("Sign in")
}
}
}
}
func choose(_ allowed: Bool) {
UserDefaults.standard.set(allowed ? "granted" : "denied", forKey: "diagnostics")
Lyrelog.setConsent(allowed ? .granted : .denied)
}Flush and stop
On iOS, tvOS and visionOS, going to the background already flushes (with a background task), so you rarely need to.
await Lyrelog.flush() // write everything to disk and try to send now
await Lyrelog.stop() // send what's queued (up to 2 seconds), then stopWithout await (from synchronous code), Lyrelog.stop() stops at once and sends nothing:
events still in memory are lost, and what was queued on disk goes out after the next start.
flush respects a Retry-After the server asked for: it doesn't send sooner.
On macOS, send what's left when the app quits by holding the quit for a moment:
final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
Task {
await Lyrelog.stop() // sends what's queued, up to 2 seconds
sender.reply(toApplicationShouldTerminate: true)
}
return .terminateLater
}
}
// In your App: @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegateIn development and tests
Don't call Lyrelog.start in unit tests or previews: anything logged before start is
ignored, so the rest of your code runs unchanged.
if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil {
Lyrelog.start(Configuration(apiKey: "lyr_ing_..."))
}mirrorToOSLog: true also prints every event to Xcode's console while you work.
Verified events
A verified event is one that can't have been sent by someone who copied the public ingest key out of an app or a web page. What that proves, and what it doesn't, is on Verified events.
On a real iPhone, iPad or Apple Watch, the SDK proves with Apple's App Attest that events come
from your genuine app, and Lyrelog stores them as verified (verified_by is app_attest). The
option appAttest is true by default; it needs:
- The App Attest capability on the app target (Signing & Capabilities), the entitlement
com.apple.developer.devicecheck.appattest-environment. Set it toproductionfor App Store and TestFlight builds; without it Apple uses the development environment. - Your App ID, the Team ID, a dot and the bundle id (
ABCDE12345.com.example.app), in the project's settings, section Verified events from your Apple apps. Until it's set, the SDK stops trying for that launch.
Sending never waits for it: batches go without a token until the device has one, so the first
events of a fresh install arrive unverified, as do events sent whenever anything fails. Only the
key's id is kept, in the Keychain, and a denial of consent deletes it. Turn it off with
appAttest: false.
To check, open the explorer: in Filter, pick Verified by and App Attest (the other values are Server key and Not verified). An opened event says it under Context, in its Sender line: Verified, App Attest, or Not verified, public key.
Macs (Apple doesn't offer App Attest there), the simulator, app extensions (except on watchOS) and devices without App Attest always send unverified events, even with everything set up: the ingest key is public, so anyone holding it could have sent the same. A verified event proves which app sent it, not that what it says is true.
See Verified events for who verifies what and the daily share.
Configuration
| Option | Default | Meaning |
|---|---|---|
endpoint | https://ingest.lyrelog.com | The base URL; a pasted /v1/... path is stripped. https only, http only for localhost |
apiKey | required | The project's ingest key |
consent | .granted | .pending, .granted or .denied |
minimumLevel | .debug | Events below it never reach the disk |
mirrorToOSLog | false | Also print every event to the unified log (Console, Xcode) |
uploadInterval | 15 s | How often the uploader wakes in the foreground |
pauseUploadsInLowPowerMode | true | Periodic uploads pause; going to the background still sends |
maxBatchBytes | 512 KiB | A batch closes at whichever limit comes first (kept between 64 KiB and 4 MiB) |
maxBatchEvents | 500 | At most 2,000 |
maxDiskBytes | 20 MB | Cap on the queue on disk, oldest first |
maxEventAge | 7 days | Older queued events are dropped |
sessionTimeout | 30 min | Idle time that starts a new session |
storageDirectory | Library/Caches/lyrelog | Where the queue lives |
captureDiagnostics | true | MetricKit crashes, hangs and overuse reports |
attachScreen | true | Tag events with the current screen |
environment | detected | Any valid name, or nil |
platform | the OS | Any valid name, or nil |
appAttest | true | Verify events with Apple's App Attest on supported devices |
Delivery and limits
| Never blocks | Logging copies the event and returns; one background writer puts it on disk. |
| Survives kills and offline | A queue in Library/Caches, capped at 20 MB and 7 days. The system may purge Caches when the device is short of space, and the waiting events go with it. |
| Batches | Up to 500 events or 512 KiB per request, gzipped. An event over 1 MiB once encoded is dropped and counted. |
| Retries | 1 s doubling to 5 min, with full jitter, honoring Retry-After. Any other 4xx drops the batch, a 3xx (a redirect, never followed) drops it with a warning, and a revoked key (401, 403) stops sending until the next launch. A batch the server keeps failing while others go through goes to the back, then is dropped. |
| Monthly quota | When a Free organization has used its month's events, the server answers 429. Events stay in the queue on disk and go out once the server takes them again, within the 20 MB and 7 day caps. The SDK logs one warning (unified log, subsystem com.lyrelog.sdk) per quota stop. |
| Drops are visible | Events lost to the caps become one lyrelog_events_dropped warning (area lyrelog) with the count. |
| Its own problems | A wrong endpoint, a refused key or rejected lines go once per launch to the unified log, subsystem com.lyrelog.sdk, at debug level (in Console, turn on Include Debug Messages). |
| Context | App id, version, build, OS, device model (iPhone18,1), locale, session id and install id. |
| Secrets | Values under keys whose name is or ends with authorization, cookie, password, token, secret, apikey and the rest of the shared list become "[redacted]", at any depth, before anything is cut. |
| Limits | Long strings cut on a character boundary, extra attributes counted in lyrelog_dropped_attrs, payloads over 64 KiB summarized as {"lyrelog_truncated": true, "bytes": N, "preview": "..."}. |
Change the list with redactedKeys: your list replaces the defaults, and [] turns redaction
off. To add to it:
Lyrelog.start(Configuration(
apiKey: "lyr_ing_...",
redactedKeys: Lyrelog.Configuration.defaultRedactedKeys + ["pin"]
))Privacy manifest and App Store privacy
The package ships a privacy manifest (PrivacyInfo.xcprivacy) that Xcode merges into your app's
privacy report: no tracking, no tracking domains, the file timestamp API with reason C617.1
(the queue reads its own files' sizes), and the data it collects (crash data, performance data,
other diagnostic data, a device id), not linked to the person and not used for tracking.
For the App Store privacy label, declare what your app sends through Lyrelog:
- Diagnostics: Crash Data, Performance Data, Other Diagnostic Data (App Functionality).
- Identifiers > Device ID: the install id, a random UUID that isn't the advertising id,
isn't backed up and is deleted on a denial (App Functionality). Not linked to the person
unless you also call
setUser. - Identifiers > User ID, linked to the person: only if you call
setUser. - Usage Data > Product Interaction: if you log screens (
screen_viewed) or taps. - Anything else your
attrsorpayloadcarry (emails, purchases...), under its own category.
The server adds the country of the sending address; the address itself isn't stored.