/diagnostics:diagnostics-swiftfrom diagnostics
Language-specific logging, error handling, and diagnostics patterns for Swift. Extends diagnostics-base with concrete Swift library choices (swift-log, os.Logger, native Error / LocalizedError, typed throws, Result) and idiomatic code patterns for both Apple-platform apps and server-side Swift. Triggers whenever writing or reviewing error types, log calls, do/try/catch blocks, or diagnostic code in Swift. REQUIRES diagnostics-base to be installed — this skill does not repeat base rules, it extends them.
Ships in diagnostics. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
REQUIRED: Read
diagnostics-basefully before applying any pattern here. This skill extends diagnostics-base — it does not repeat base rules. All rules in diagnostics-base apply unchanged. This skill adds Swift-specific library choices, syntax, and idiomatic patterns on top of them.
The idiomatic Swift diagnostics stack is almost entirely stdlib plus one Apple package:
| Role | Library | Notes |
|---|---|---|
| Logging (cross-platform) | apple/swift-log (Logging) | Server-side default; Vapor/Hummingbird use it |
| Logging (Apple-only) | os.Logger (OSLog) | Apple platforms only; Console.app / Instruments; privacy-aware interpolation |
| Bridge | swift-log + OSLog backend | When an Apple app pulls in libraries that log via swift-log |
| Error types | Swift stdlib Error + custom enum | Conform to LocalizedError and CustomNSError |
| Typed throws | throws(SpecificError) (Swift 6+) | Use in libraries; callers must exhaustively match |
| Result type | Result<Success, Failure: Error> | Use only at boundaries with non-throwing callbacks |
| Validation | Codable + custom validators (or Vapor.Validation) | See references/validation.md |
| Tracing/metrics | swift-distributed-tracing, swift-metrics | Integrate via Logger.MetadataValue |
If a project uses a different stack, update this table and regenerate the skill — the patterns below assume the libraries above.
The most common confusion in Swift diagnostics is swift-log vs os.Logger
vs print. Resolve it with these three trees.
For SERVER, CLI, or SHARED LIBRARY code (anything that may run on Linux, or
anything published as a SwiftPM package):
→ use `swift-log` (`import Logging`)
cross-platform; library callers can swap the backend; SSWG-blessed
For Apple-only APP TARGETS (iOS / macOS / tvOS / watchOS / visionOS):
→ use `os.Logger` (`import OSLog`)
zero-dependency; Console.app/Instruments integration;
privacy-aware interpolation; lowest overhead
For SHARED packages USED BY Apple apps:
→ use `swift-log` so the package stays portable;
the app target bridges it to OSLog via a LoggingOSLog backend
For PUBLIC libraries / SwiftPM packages (others depend on them):
→ typed error enum + `throws(MyError)` (Swift 6 typed throws)
callers must exhaustively match on specific cases
For APPLICATIONS (app target, CLI main, HTTP handler — owns the error boundary):
→ untyped `throws` is fine; wrap with context at each layer;
conform the top-level error type to `LocalizedError`
For OLD CALLBACK APIs or non-throwing async streams:
→ use `Result<Success, Failure: Error>` to bridge
For NEW CODE:
→ prefer `throws` / `async throws` — Swift's preferred error channel
For rendering errors to END USERS (UI / CLI stderr): conform error types to
LocalizedError (errorDescription, failureReason, recoverySuggestion,
helpAnchor) plus CustomNSError (errorCode, errorUserInfo) for stable
telemetry.
swift-log// File: Sources/MyApp/Logging+Setup.swift
// Base rule: diagnostics-base §Log Setup
import Logging
enum LoggingSetup {
static func bootstrap() {
let level = ProcessInfo.processInfo.environment["LOG_LEVEL"]
.flatMap(Logger.Level.init(rawValue:)) ?? .info
#if DEBUG
// Dev: pretty, human-readable
LoggingSystem.bootstrap { label in
var handler = StreamLogHandler.standardOutput(label: label)
handler.logLevel = level
return handler
}
#else
// Production: JSON one-line-per-event
LoggingSystem.bootstrap { label in
var handler = JSONLogHandler(label: label, stream: .stdout)
handler.logLevel = level
return handler
}
#endif
}
}
// Per-subsystem loggers — never one global logger. Each module gets its own
// labeled logger so queries can filter by source.
extension Logger {
static let auth = Logger(label: "myapp.auth")
static let billing = Logger(label: "myapp.billing")
static let http = Logger(label: "myapp.http")
}
os.Logger// File: MyApp/Diagnostics/Loggers.swift
import OSLog
extension Logger {
static let auth = Logger(subsystem: "io.tarq.MyApp", category: "auth")
static let billing = Logger(subsystem: "io.tarq.MyApp", category: "billing")
static let network = Logger(subsystem: "io.tarq.MyApp", category: "network")
}
Configuration decisions:
LOG_LEVEL env var (server) / build-config (Apple) — raisable without redeploy\(value, privacy: .private)) on Apple; swift-log has no built-in redaction — wrap sensitive values in a Redacted type or strip them before adding to Logger.Metadata✅ Correct — structured fields (base rule: §Structured logging)
Logger.billing.info(
"charge attempt completed",
metadata: [
"user_id": "\(userID)",
"charge_id": "\(chargeID)",
"amount_cents": "\(amount)",
"currency": "\(currency)",
"trace_id": "\(traceID)",
"error.code": "\(error?.errorCode ?? "")",
]
)
❌ Wrong — interpolated string
Logger.billing.info("charged user \(userID) $\(amount) (trace \(traceID))")
// Filtering on user_id, sorting by amount, joining on trace_id all become regex.
The message string is a stable description of the event ("charge attempt
completed"); all data goes in metadata.
os.Logger is unusual: string interpolation IS structured — each
interpolated value carries a privacy tag, and OSLog stores the parts
separately for redaction and indexing.
✅ Correct — privacy tags on every dynamic value
Logger.billing.info(
"charge attempt completed user=\(userID, privacy: .private(mask: .hash)) \
charge=\(chargeID, privacy: .public) \
amount_cents=\(amount, privacy: .public)"
)
❌ Wrong — no privacy annotation = defaults to .private and gets redacted
in production exports.
Logger.billing.info("charged user \(userID) $\(amount)")
// In production: "charged user <private> $<private>"
func handleRequest(_ req: Request) async {
let traceID = req.headers.first(name: "x-trace-id") ?? UUID().uuidString
var log = Logger.http
log[metadataKey: "trace_id"] = "\(traceID)"
log[metadataKey: "route"] = "\(req.route)"
// every log call on `log` below carries trace_id and route
await processRequest(req, log: log)
}
For distributed tracing, use swift-distributed-tracing's ServiceContext
(propagates trace IDs across async); swift-log integrates via
MetadataProvider.
// File: Sources/UserStore/UserStoreError.swift
// Base rule: diagnostics-base §Error taxonomy
public enum UserStoreError: Error, LocalizedError, CustomNSError {
case notFound(userID: UUID)
case databaseUnavailable(underlying: any Error)
case rateLimited(retryAfter: Duration)
case malformedRecord(field: String, reason: String, underlying: any Error)
public var code: String {
switch self {
case .notFound: return "USER_STORE.NOT_FOUND"
case .databaseUnavailable: return "USER_STORE.DB_UNAVAILABLE"
case .rateLimited: return "USER_STORE.RATE_LIMITED"
case .malformedRecord: return "USER_STORE.MALFORMED_RECORD"
}
}
public var source: ErrorSource {
switch self {
case .notFound, .malformedRecord: return .user
case .databaseUnavailable, .rateLimited: return .dependency
}
}
public var isRetriable: Bool {
switch self {
case .databaseUnavailable, .rateLimited: return true
case .notFound, .malformedRecord: return false
}
}
public var errorDescription: String? {
switch self {
case .notFound(let id):
return "We couldn't find user \(id.uuidString)."
case .databaseUnavailable:
return "The user database is temporarily unavailable. Please try again."
case .rateLimited(let retry):
return "Too many requests. Try again in \(retry.components.seconds)s."
case .malformedRecord(let field, let reason, _):
return "User record has an invalid \(field): \(reason)."
}
}
public static var errorDomain: String { "io.tarq.UserStore" }
public var errorCode: Int {
switch self {
case .notFound: return 1001
case .databaseUnavailable: return 1002
case .rateLimited: return 1003
case .malformedRecord: return 1004
}
}
public var errorUserInfo: [String: Any] {
var info: [String: Any] = ["code": code, "retriable": isRetriable]
if case .malformedRecord(let field, _, let underlying) = self {
info["field"] = field
info[NSUnderlyingErrorKey] = underlying
}
if case .databaseUnavailable(let underlying) = self {
info[NSUnderlyingErrorKey] = underlying
}
return info
}
}
public enum ErrorSource: String, Sendable {
case user, dependency, bug, infra
}
// Callers must exhaustively handle UserStoreError variants
public func loadUser(id: UUID) async throws(UserStoreError) -> User {
do {
return try await db.fetch(id)
} catch let dbError as DatabaseError where dbError.isConnectivity {
throw .databaseUnavailable(underlying: dbError)
} catch let dbError as DatabaseError where dbError.isRateLimit {
throw .rateLimited(retryAfter: .seconds(dbError.retryAfter))
} catch {
throw .malformedRecord(field: "unknown", reason: "decode failed", underlying: error)
}
}
In app code, untyped throws plus context-wrapping at each layer is the
right shape — the boundary owns the error type:
struct AppError: Error, LocalizedError {
let message: String
let underlying: (any Error)?
let metadata: [String: String]
init(_ message: String,
underlying: (any Error)? = nil,
metadata: [String: String] = [:]) {
self.message = message
self.underlying = underlying
self.metadata = metadata
}
var errorDescription: String? { message }
}
func checkoutCart(userID: UUID) async throws {
do {
let user = try await loadUser(id: userID)
try await processCheckout(user: user)
} catch {
throw AppError(
"checkout failed while loading user",
underlying: error,
metadata: ["user_id": userID.uuidString]
)
}
}
Swift has no built-in cause chain like Java's Throwable.cause or Rust's
source(). Wire it manually with these conventions:
CustomNSError.errorUserInfo[NSUnderlyingErrorKey] holds the underlying errorunderlying: (any Error)? property on bespoke error types✅ Correct — cause preserved with new context at each layer
// Repository layer
do {
return try await sqlClient.query(stmt)
} catch let sql as SQLError {
throw UserStoreError.databaseUnavailable(underlying: sql)
}
// Service layer
do {
return try await userStore.load(id: id)
} catch let store as UserStoreError {
throw AppError(
"could not load user for checkout",
underlying: store,
metadata: ["user_id": id.uuidString, "stage": "load"]
)
}
A walkCauses(_:) helper that boundary handlers can call to log the chain:
func walkCauses(_ err: any Error) -> [String] {
var chain: [String] = ["\(type(of: err)): \(err.localizedDescription)"]
var current: (any Error)? = err
while let e = current {
if let app = e as? AppError, let next = app.underlying {
chain.append("\(type(of: next)): \(next.localizedDescription)")
current = next
} else if let ns = (e as NSError).userInfo[NSUnderlyingErrorKey] as? any Error {
chain.append("\(type(of: ns)): \(ns.localizedDescription)")
current = ns
} else {
current = nil
}
}
return chain
}
❌ Wrong — cause swallowed; only the top-level message survives
do { return try await sqlClient.query(stmt) }
catch { throw UserStoreError.databaseUnavailable(underlying: GenericError()) } // lost SQLError
Every catch that re-throws MUST pass the caught error through as
underlying (or as an associated value on a typed throw). Each layer adds
NEW information ("while loading user 12345") — never reword the same message
at a higher level.
Swift conventions on top of base rules:
LocalizedError.errorDescription ends with a period — it's a sentence shown to humans"failed to <verb> <noun>" over "<noun> error" — names the action that failederrorDescription — that belongs in log fieldserror.localizedDescription verbatim — Swift stdlib often returns "The operation couldn't be completed." Add domain contextLog at the boundary that decides recovery; propagate everywhere else.
Inner layers throw with added context — they do NOT log.
The boundary decides:
diagnostics-base taxonomy: user errors = INFO, dependency failures = WARN, bugs = ERROR)trace_id, user_id, error.code, error.chain)Full boundary handler implementations for HTTP (Hummingbird/Vapor), CLI
(@main + ArgumentParser), and queue-consumer patterns live in
references/boundary-examples.md — consult that file when implementing
a boundary handler.
Validation errors are user errors (base taxonomy: source=user):
DecodingError unwrapping, ValidationError wrapper type, business-rule
validation, and Vapor's Validatable integration live in
references/validation.md.
Base rule: §Retriability — callers should not parse messages to decide whether to retry.
public protocol Retriable {
var isRetriable: Bool { get }
var retryAfter: Duration? { get }
}
extension UserStoreError: Retriable {
public var retryAfter: Duration? {
if case .rateLimited(let d) = self { return d }
return nil
}
}
func withRetry<T>(
attempts: Int = 3,
log: Logger,
op: () async throws -> T
) async throws -> T {
var lastError: any Error = AppError("retry exhausted")
for attempt in 1...attempts {
do { return try await op() }
catch let r as any Retriable where r.isRetriable {
lastError = r as! any Error
let wait = r.retryAfter ?? .milliseconds(100 * Int(pow(2.0, Double(attempt))))
log.warning("operation failed, retrying",
metadata: ["attempt": "\(attempt)", "wait_ms": "\(wait.components.seconds * 1000)"])
try await Task.sleep(for: wait)
} catch {
throw error // non-retriable, surface immediately
}
}
throw lastError
}
Swift Concurrency introduces three failure modes the base skill does not cover:
CancellationError is NOT a failure. Treat as .debug or silent — never .error. Pattern-match it first in every catch.CancellationError.Logger and Logger.Metadata are Sendable — safe to capture in Tasks and pass across actors.Full patterns and code examples live in references/concurrency.md.
Apply AFTER the base skill checklist:
swift-log for cross-platform / packages, os.Logger only in Apple app targets, never print(...) in production code pathsos.Logger interpolation has a privacy: tag? (Untagged values default to .private and get redacted.)metadata: / structured fields? (No Logger.info("user \(id) did x").)LocalizedError AND CustomNSError and exposes a stable code: String?catch that re-throws passes the caught error through as underlying: (or as an associated value on a typed-throws enum)?throws(SpecificError) (Swift 6 typed throws) so callers can exhaustively match?CancellationError paths are NOT logged as .error — .debug or silent?throw with added context..info (not .error) with HTTP 400 and a field-path message?Loggers (one per module) — not one global logger?| Swift Anti-pattern | Fix |
|---|---|
print(...) / NSLog(...) for production diagnostics | Use Logger (swift-log or os.Logger) |
catch { print(error) } swallowing without re-throw | Rethrow with context, or handle explicitly with a logged decision |
throw NSError(domain: "x", code: -1, ...) ad-hoc at call sites | Define a typed error enum once; conform to LocalizedError/CustomNSError |
os.Logger interpolation with no privacy: tag on user data | Tag every dynamic value: \(id, privacy: .private(mask: .hash)) |
Logging error.localizedDescription only (loses chain) | Walk causes with walkCauses(_:); log error.chain field |
catch is CancellationError logged as .error | Cancellation is a clean signal: .debug or silent |
| Inner layer logs error, then boundary logs the same error | Remove the inner log — "log once at the boundary" |
Result<T, Error> with the existential Error type | Prefer throws; reserve Result for non-throwing bridges |
One global Logger.shared for the whole app | Per-subsystem loggers: Logger.auth, Logger.billing |
Validation errors returning HTTP 500 / log level .error | They are user errors: HTTP 400, log level .info, surface field path |
try? to convert errors to nil losing all context | Only at true presentation boundaries; otherwise propagate with try |
fatalError(...) for runtime user-error conditions | Reserve for programmer bugs / invariant violations |
For detailed patterns referenced from the sections above:
references/boundary-examples.md — Full HTTP (Hummingbird/Vapor), CLI (@main + ArgumentParser), and queue-consumer boundary handler implementationsreferences/concurrency.md — CancellationError handling, TaskGroup error aggregation, actor isolation, AsyncSequence propagationreferences/validation.md — DecodingError unwrapping, ValidationError wrapper, business-rule validation, Vapor's Validatable integrationswift-log: https://github.com/apple/swift-logos.Logger / OSLog: https://developer.apple.com/documentation/os/loggerswift-distributed-tracing: https://github.com/apple/swift-distributed-tracingswift-metrics: https://github.com/apple/swift-metricsdiagnostics-base: installed alongside this skillWhat SKILL.md sets; muted values are Claude Code's defaults
diagnostics@tarq is listed by tarqd/skills — review the source before installing
npx claudepluginhub tarqd/skills --plugin diagnosticsOther plugins' skills for the same job
4 skills in this plugin
/diagnostics-baseThis skill should be used whenever writing, reviewing, or refactoring error types, error messages, log statements, or any code that reports failure to a human or a machine — e.g. defining an `Error`/`Exception` class, writing `throw`, `panic!`, `raise`, or `return Err(...)`, calling `log.info/warn/error`, `console.error`, `slog`, `tracing`, `logger.*`, or composing user-facing error messages. Language-agnostic foundations; pair with a language-specific diagnostics skill for library/crate/package choices.
/diagnostics-lang-skill-creatorWorkflow skill that creates a language-specific logging and diagnostics skill for a given programming language. Invoke ONLY when the user explicitly asks to create or generate a diagnostics skill, logging skill, or error handling skill for a specific language — e.g. "create a TypeScript diagnostics skill", "build me a Rust logging skill", "make a Go error handling skill for my project", "generate a Python diagnostics skill". Do NOT trigger for general questions about logging or error handling — only when the user wants to produce a new skill artifact. This skill is a multi-phase interactive workflow; do not attempt to run it silently or skip user checkpoints. Requires the diagnostics-base skill to be installed.