Custom sinks
In Logly, a sink is an additional destination for log messages. It does not receive a finished text line but a LogEvent with all individual values, including the original Error. The Sentry integration is itself a sink.
The LogSink protocol
A custom Logly sink implements the LogSink protocol:
public protocol LogSink: Sendable {
func emit(_ event: LogEvent)
}
The LogEvent event
The following table lists the fields of LogEvent that Logly passes to every sink:
| Field | Type | Content |
|---|---|---|
level | LogLevel | Level of the message |
category | String | Category name, without padding or truncation |
message | String | Message text, unformatted |
error | (any Error)? | Error passed to error(_:error:) or fault(_:error:), otherwise nil |
file | String | Value of #file at the call site, e.g. MyApp/APIClient.swift |
line | Int | Line number at the call site |
timestamp | Date | Time of the log call |
When Logly calls a sink
Logly calls a sink under these conditions:
- Only for messages that pass the level filter (
currentLogLevel). - Regardless of
logToFile. - After console output and file access.
- With
asynchronousLogging = trueon the serial logging queue, otherwise on the calling thread.
A sink should therefore be thread-safe and fast. Hand long-running work such as network calls off to your own queue or task.
Registering and removing sinks in Logly
You register and remove sinks through LoggerConfiguration.shared:
LoggerConfiguration.shared.addSink(MySink())
let registered = LoggerConfiguration.shared.sinks // read-only
LoggerConfiguration.shared.removeAllSinks()
In Logly you cannot remove a single sink, only all of them at once. removeAllSinks() also removes the Sentry sink.
Custom Logly sink examples
Sink for an in-app log view
This Logly sink is a ring buffer that keeps the last 500 messages in memory, e.g. for a debug screen:
import Logly
import os
final class InMemoryLogSink: LogSink {
static let shared = InMemoryLogSink()
private let buffer = OSAllocatedUnfairLock(initialState: [LogEvent]())
private let capacity = 500
func emit(_ event: LogEvent) {
buffer.withLock { events in
events.append(event)
if events.count > capacity {
events.removeFirst(events.count - capacity)
}
}
}
var events: [LogEvent] {
buffer.withLock { $0 }
}
}
// At startup
LoggerConfiguration.shared.addSink(InMemoryLogSink.shared)
This is how you display the messages from the ring buffer in SwiftUI:
struct LogConsoleView: View {
@State private var events: [LogEvent] = []
var body: some View {
List(events.indices.reversed(), id: \.self) { index in
let event = events[index]
VStack(alignment: .leading) {
Text("\(event.level.description) · \(event.category)")
.font(.caption.monospaced())
Text(event.message)
}
}
.refreshable { events = InMemoryLogSink.shared.events }
.onAppear { events = InMemoryLogSink.shared.events }
}
}
Logly sink that forwards errors only
This Logly sink is a sink that notifies your own service from level .error upwards and decouples the work from the logging thread:
struct ErrorReportingSink: LogSink {
func emit(_ event: LogEvent) {
guard event.level.rawValue >= LogLevel.error.rawValue else { return }
let category = event.category
let message = event.message
let errorDescription = event.error.map { String(describing: $0) }
Task.detached {
await ErrorReporter.shared.report(category: category,
message: message,
error: errorDescription)
}
}
}
ErrorReporter stands for your own service.
Logly sink for a JSON Lines file
This Logly sink writes every event as a JSON object to a separate file, e.g. for automated analysis:
import Foundation
import Logly
import os
final class JSONLinesSink: LogSink {
private struct Line: Encodable {
let timestamp: Date
let level: String
let category: String
let message: String
let error: String?
let file: String
let line: Int
}
private let url: URL
private let lock = OSAllocatedUnfairLock()
init(url: URL) { self.url = url }
func emit(_ event: LogEvent) {
let line = Line(timestamp: event.timestamp,
level: event.level.description,
category: event.category,
message: event.message,
error: event.error.map { String(describing: $0) },
file: event.file,
line: event.line)
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
guard let json = try? encoder.encode(line) else { return }
let data = json + Data([0x0A]) // line break
lock.withLock {
if let handle = try? FileHandle(forWritingTo: url) {
handle.seekToEndOfFile()
handle.write(data)
handle.closeFile()
} else {
try? data.write(to: url)
}
}
}
}
Checking Logly messages in unit tests
With a sink that collects all events, you check Logly messages in unit tests:
import XCTest
import Logly
import os
final class CapturingSink: LogSink {
private let storage = OSAllocatedUnfairLock(initialState: [LogEvent]())
func emit(_ event: LogEvent) { storage.withLock { $0.append(event) } }
var events: [LogEvent] { storage.withLock { $0 } }
}
final class CheckoutTests: XCTestCase {
override func setUp() {
super.setUp()
let config = LoggerConfiguration.shared
config.asynchronousLogging = false // call sinks immediately
config.logToFile = false
config.removeAllSinks()
}
func testFailedPaymentIsLoggedAsError() {
let sink = CapturingSink()
LoggerConfiguration.shared.addSink(sink)
Logger.custom(category: "Checkout").error("Payment declined")
XCTAssertEqual(sink.events.count, 1)
XCTAssertEqual(sink.events.first?.level, .error)
XCTAssertEqual(sink.events.first?.category, "Checkout")
}
}
LoggerConfiguration.shared is global. Tests running in parallel share sinks and settings.