Skip to content

Commit c05d672

Browse files
authored
Overhaul README and documentation catalog to introduce best practices (#363)
# Motivation `SwiftLog` was created before DocC existed which meant that most of the documentation was part of the `README` and we had a pretty bare bones documentation catalog. We also have a second source of guidelines from the SSWG. This results in a currently unsatisfying developer experience where everyone has to go around looking for the content in mostly undocumented places. # Modifications This PR overhauls the `README` and moves most of the content into the documentation catalog. It also introduces a new section called "Best practices" that are intended to replace the logging guides on swift.org so that the content moves closer to where it belongs. To showcase such a best practice this PR brings over the log level recommendation of swift.org. The recommendation is mostly the same except that after recent discussions we wanted to allow libraries to log at `info` level when they encounter problems which they can't communicate through other channels e.g. by throwing from a method. # Result With this PR we provide a nicer experience to our developers making it easier for them to get started and understand how to properly log. We also set ourselves up for expanding on the best practices around logging.
1 parent 2281e43 commit c05d672

File tree

5 files changed

+366
-224
lines changed

5 files changed

+366
-224
lines changed

README.md

Lines changed: 45 additions & 205 deletions
Original file line numberDiff line numberDiff line change
@@ -1,224 +1,64 @@
11
# SwiftLog
22

3-
First things first: This is the beginning of a community-driven open-source project actively seeking contributions, be it code, documentation, or ideas. Apart from contributing to `SwiftLog` itself, there's another huge gap at the moment: `SwiftLog` is an _API package_ which tries to establish a common API the ecosystem can use. To make logging really work for real-world workloads, we need `SwiftLog`-compatible _logging backends_ which then either persist the log messages in files, render them in nicer colors on the terminal, or send them over to Splunk or ELK.
3+
This repository contains a logging API implementation for Swift.
4+
SwiftLog provides a unified, performant, and ergonomic logging API that can be
5+
adopted by libraries and applications across the Swift ecosystem.
46

5-
What `SwiftLog` provides today can be found in the [API docs][api-docs].
7+
- 📚 **Documentation** and **tutorials** are available on the [Swift Package Index][spi-swift-log]
8+
- 🚀 **Contributions** are welcome, please see [CONTRIBUTING.md](CONTRIBUTING.md)
9+
- 🪪 **License** is Apache 2.0, repeated in [LICENSE.txt](LICENSE.txt)
10+
- 🔒 **Security** issues should be reported via the process in [SECURITY.md](SECURITY.md)
11+
- 🔀 **Available Logging Backends**: SwiftLog is an API package - you'll want to
12+
choose from the many
13+
[community-maintained logging backends](#available-log-handler-backends) for production use
614

7-
## Getting started
15+
## Quick Start
816

9-
If you have a server-side Swift application, or maybe a cross-platform (for example Linux & macOS) app/library, and you would like to log, we think targeting this logging API package is a great idea. Below you'll find all you need to know to get started.
10-
11-
#### Adding the dependency
12-
13-
`SwiftLog` is designed for Swift 5.8 and later. To depend on the logging API package, you need to declare your dependency in your `Package.swift`:
14-
15-
```swift
16-
.package(url: "https://github.com/apple/swift-log.git", from: "1.0.0"),
17-
```
18-
19-
and to your application/library target, add `"Logging"` to your `dependencies`, e.g. like this:
17+
The following snippet shows how to add SwiftLog to your Swift Package:
2018

2119
```swift
22-
.target(name: "BestExampleApp", dependencies: [
23-
.product(name: "Logging", package: "swift-log")
24-
],
20+
// swift-tools-version: 6.1
21+
import PackageDescription
22+
23+
let package = Package(
24+
name: "YourApp",
25+
dependencies: [
26+
.package(url: "https://github.com/apple/swift-log", from: "1.6.0")
27+
],
28+
targets: [
29+
.target(
30+
name: "YourApp",
31+
dependencies: [
32+
.product(name: "Logging", package: "swift-log")
33+
]
34+
)
35+
]
36+
)
2537
```
2638

27-
28-
#### Let's log
39+
Then start logging:
2940

3041
```swift
31-
// 1) let's import the logging API package
3242
import Logging
3343

34-
// 2) we need to create a logger, the label works similarly to a DispatchQueue label
35-
let logger = Logger(label: "com.example.BestExampleApp.main")
36-
37-
// 3) we're now ready to use it
38-
logger.info("Hello World!")
39-
```
40-
41-
#### Output
42-
43-
```
44-
2019-03-13T15:46:38+0000 info: Hello World!
45-
```
46-
47-
#### Default `Logger` behavior
48-
49-
`SwiftLog` provides for very basic console logging out-of-the-box by way of `StreamLogHandler`. It is possible to switch the default output to `stderr` like so:
50-
```swift
51-
LoggingSystem.bootstrap(StreamLogHandler.standardError)
52-
```
53-
54-
`StreamLogHandler` is primarily a convenience only and does not provide any substantial customization. Library maintainers who aim to build their own logging backends for integration and consumption should implement the `LogHandler` protocol directly as laid out in [the "On the implementation of a logging backend" section](#on-the-implementation-of-a-logging-backend-a-loghandler).
55-
56-
For further information, please check the [API documentation][api-docs].
57-
58-
<a name="backends"></a>
59-
## Available Logging Backends For Applications
60-
61-
You can choose from one of the following backends to consume your logs. If you are interested in implementing one see the "Implementation considerations" section below explaining how to do so. List of existing SwiftLog API compatible libraries:
62-
63-
| Repository | Handler Description|
64-
| ----------- | ----------- |
65-
| [Kitura/HeliumLogger](https://github.com/Kitura/HeliumLogger) |a logging backend widely used in the Kitura ecosystem |
66-
| [ianpartridge/swift-log-**syslog**](https://github.com/ianpartridge/swift-log-syslog) | a [syslog](https://en.wikipedia.org/wiki/Syslog) backend|
67-
| [Adorkable/swift-log-**format-and-pipe**](https://github.com/Adorkable/swift-log-format-and-pipe) | a backend that allows customization of the output format and the resulting destination |
68-
| [chrisaljoudi/swift-log-**oslog**](https://github.com/chrisaljoudi/swift-log-oslog) | an OSLog [Unified Logging](https://developer.apple.com/documentation/os/logging) backend for use on Apple platforms. **Important Note:** we recommend using os_log directly as described [here](https://developer.apple.com/documentation/os/logging). Using os_log through swift-log using this backend will be less efficient and will also prevent specifying the privacy of the message. The backend always uses `%{public}@` as the format string and eagerly converts all string interpolations to strings. This has two drawbacks: 1. the static components of the string interpolation would be eagerly copied by the unified logging system, which will result in loss of performance. 2. It makes all messages public, which changes the default privacy policy of os_log, and doesn't allow specifying fine-grained privacy of sections of the message. In a separate on-going work, Swift APIs for os_log are being improved and made to align closely with swift-log APIs. References: [Unifying Logging Levels](https://forums.swift.org/t/custom-string-interpolation-and-compile-time-interpretation-applied-to-logging/18799), [Making os_log accept string interpolations using compile-time interpretation](https://forums.swift.org/t/logging-levels-for-swifts-server-side-logging-apis-and-new-os-log-apis/20365). |
69-
| [Brainfinance/StackdriverLogging](https://github.com/Brainfinance/StackdriverLogging) | a structured JSON logging backend for use on Google Cloud Platform with the [Stackdriver logging agent](https://cloud.google.com/logging/docs/agent) |
70-
| [DnV1eX/GoogleCloudLogging](https://github.com/DnV1eX/GoogleCloudLogging) | a client-side library for logging application events in [Google Cloud](https://console.cloud.google.com/logs) via REST API v2. |
71-
| [vapor/console-kit](https://github.com/vapor/console-kit/) | a logger to the current terminal or stdout with stylized ([ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code)) output. The default logger for all Vapor applications |
72-
| [neallester/swift-log-testing](https://github.com/neallester/swift-log-testing) | provides access to log messages for use in assertions (within test targets) |
73-
| [wlisac/swift-log-slack](https://github.com/wlisac/swift-log-slack) | a logging backend that sends critical log messages to Slack |
74-
| [NSHipster/swift-log-github-actions](https://github.com/NSHipster/swift-log-github-actions) | a logging backend that translates logging messages into [workflow commands for GitHub Actions](https://help.github.com/en/actions/reference/workflow-commands-for-github-actions). |
75-
| [stevapple/swift-log-telegram](https://github.com/stevapple/swift-log-telegram) | a logging backend that sends log messages to any Telegram chat (Inspired by and forked from [wlisac/swift-log-slack](https://github.com/wlisac/swift-log-slack)) |
76-
| [jagreenwood/swift-log-datadog](https://github.com/jagreenwood/swift-log-datadog) | a logging backend which sends log messages to the [Datadog](https://www.datadoghq.com/log-management/) log management service |
77-
| [google/SwiftLogFireCloud](https://github.com/google/swiftlogfirecloud) | a logging backend for time series logging which pushes logs as flat files to Firebase Cloud Storage. |
78-
| [crspybits/swift-log-file](https://github.com/crspybits/swift-log-file) | a simple local file logger (using `Foundation` `FileManager`) |
79-
| [sushichop/Puppy](https://github.com/sushichop/Puppy) | a logging backend that supports multiple transports(console, file, syslog, etc.) and has the feature with formatting and file log rotation |
80-
| [ShivaHuang/swift-log-SwiftyBeaver](https://github.com/ShivaHuang/swift-log-SwiftyBeaver) | a logging backend for printing colored logging to Xcode console / file, or sending encrypted logging to [SwiftyBeaver](https://swiftybeaver.com) platform. |
81-
| [Apodini/swift-log-elk](https://github.com/Apodini/swift-log-elk) | a logging backend that formats, caches and sends log data to [elastic/logstash](https://github.com/elastic/logstash) |
82-
| [binaryscraping/swift-log-supabase](https://github.com/binaryscraping/swift-log-supabase) | a logging backend that sends log entries to [Supabase](https://github.com/supabase/supabase). |
83-
| [kiliankoe/swift-log-matrix](https://swiftpackageindex.com/kiliankoe/swift-log-matrix) | a logging backend for sending logs directly to a [Matrix](https://matrix.org) room |
84-
| [DiscordBM/DiscordLogger](https://github.com/DiscordBM/DiscordLogger) | a Discord logging implementation to send your logs over to a Discord channel in a good-looking manner and with a lot of configuration options including the ability to send only a few important log-levels such as `warning`/`error`/`critical`. |
85-
| [CocoaLumberjack](https://github.com/CocoaLumberjack/CocoaLumberjack) | a fast & simple, yet powerful & flexible logging framework for macOS, iOS, tvOS and watchOS, which includes a logging backend for swift-log. |
86-
| [rwbutler/swift-log-ecs](https://github.com/rwbutler/swift-log-ecs) | a logging backend for logging in [ECS Log format](https://www.elastic.co/guide/en/ecs-logging/overview/current/intro.html). Compatible with [Vapor](https://github.com/vapor/vapor) and allows chaining of multiple LogHandlers. |
87-
| [ShipBook/swift-log-**shipbook**](https://github.com/ShipBook/swift-log-shipbook) | a logging backend that sends log entries to [Shipbook](https://www.shipbook.io) - Shipbook gives you the power to remotely gather, search and analyze your user logs and exceptions in the cloud, on a per-user & session basis. |
88-
| [kasianov-mikhail/scout](https://github.com/kasianov-mikhail/scout) | CloudKit as a log storage |
89-
| [PADL/AndroidLogging](https://github.com/PADL/AndroidLogging) | a logging backend for the Android in-kernel log buffer |
90-
| [xtremekforever/swift-systemd](https://github.com/xtremekforever/swift-systemd) | a logging backend for the [systemd](https://systemd.io/) journal |
91-
| Your library? | [Get in touch!](https://forums.swift.org/c/server) |
92-
93-
## What is an API package?
94-
95-
Glad you asked. We believe that for the Swift on Server ecosystem, it's crucial to have a logging API that can be adopted by anybody so a multitude of libraries from different parties can all log to a shared destination. More concretely this means that we believe all the log messages from all libraries end up in the same file, database, Elastic Stack/Splunk instance, or whatever you may choose.
96-
97-
In the real-world however, there are so many opinions over how exactly a logging system should behave, what a log message should be formatted like, and where/how it should be persisted. We think it's not feasible to wait for one logging package to support everything that a specific deployment needs whilst still being easy enough to use and remain performant. That's why we decided to cut the problem in half:
98-
99-
1. a logging API
100-
2. a logging backend implementation
101-
102-
This package only provides the logging API itself and therefore `SwiftLog` is a 'logging API package'. `SwiftLog` (using `LoggingSystem.bootstrap`) can be configured to choose any compatible logging backend implementation. This way packages can adopt the API and the _application_ can choose any compatible logging backend implementation without requiring any changes from any of the libraries.
103-
104-
Just for completeness sake: This API package does actually include an overly simplistic and non-configurable logging backend implementation which simply writes all log messages to `stdout`. The reason to include this overly simplistic logging backend implementation is to improve the first-time usage experience. Let's assume you start a project and try out `SwiftLog` for the first time, it's just a whole lot better to see something you logged appear on `stdout` in a simplistic format rather than nothing happening at all. For any real-world application, we advise configuring another logging backend implementation that logs in the style you like.
105-
106-
## The core concepts
107-
108-
### Loggers
109-
110-
`Logger`s are used to emit log messages and therefore the most important type in `SwiftLog`, so their use should be as simple as possible. Most commonly, they are used to emit log messages in a certain log level. For example:
111-
112-
```swift
113-
// logging an informational message
114-
logger.info("Hello World!")
115-
116-
// ouch, something went wrong
117-
logger.error("Houston, we have a problem: \(problem)")
118-
```
119-
120-
### Log levels
121-
122-
The following log levels are supported:
123-
124-
- `trace`
125-
- `debug`
126-
- `info`
127-
- `notice`
128-
- `warning`
129-
- `error`
130-
- `critical`
131-
132-
The log level of a given logger can be changed, but the change will only affect the specific logger you changed it on. You could say the `Logger` is a _value type_ regarding the log level.
44+
// Create a logger
45+
let logger = Logger(label: "com.example.YourApp")
13346

47+
// Log at different levels
48+
logger.info("Application started")
49+
logger.warning("This is a warning")
50+
logger.error("Something went wrong", metadata: ["error": "\(error)"])
13451

135-
### Logging metadata
136-
137-
Logging metadata is metadata that can be attached to loggers to add information that is crucial when debugging a problem. In servers, the usual example is attaching a request UUID to a logger that will then be present on all log messages logged with that logger. Example:
138-
139-
```swift
140-
var logger = logger
141-
logger[metadataKey: "request-uuid"] = "\(UUID())"
142-
logger.info("hello world")
143-
```
144-
145-
will print
146-
147-
```
148-
2019-03-13T18:30:02+0000 info: request-uuid=F8633013-3DD8-481C-9256-B296E43443ED hello world
149-
```
150-
151-
with the default logging backend implementation that ships with `SwiftLog`. Needless to say, the format is fully defined by the logging backend you choose.
152-
153-
## On the implementation of a logging backend (a `LogHandler`)
154-
155-
Note: If you don't want to implement a custom logging backend, everything in this section is probably not very relevant, so please feel free to skip.
156-
157-
To become a compatible logging backend that all `SwiftLog` consumers can use, you need to do two things: 1) Implement a type (usually a `struct`) that implements `LogHandler`, a protocol provided by `SwiftLog` and 2) instruct `SwiftLog` to use your logging backend implementation.
158-
159-
A `LogHandler` or logging backend implementation is anything that conforms to the following protocol
160-
161-
```swift
162-
public protocol LogHandler {
163-
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, source: String, file: String, function: String, line: UInt)
164-
165-
subscript(metadataKey _: String) -> Logger.Metadata.Value? { get set }
166-
167-
var metadata: Logger.Metadata { get set }
168-
169-
var logLevel: Logger.Level { get set }
170-
}
52+
// Add metadata for context
53+
var requestLogger = logger
54+
requestLogger[metadataKey: "request-id"] = "\(UUID())"
55+
requestLogger.info("Processing request")
17156
```
17257

173-
Instructing `SwiftLog` to use your logging backend as the one the whole application (including all libraries) should use is very simple:
174-
175-
```swift
176-
LoggingSystem.bootstrap(MyLogHandler.init)
177-
```
178-
179-
### Implementation considerations
180-
181-
`LogHandler`s control most parts of the logging system:
182-
183-
#### Under control of a `LogHandler`
184-
185-
##### Configuration
186-
187-
`LogHandler`s control the two crucial pieces of `Logger` configuration, namely:
188-
189-
- log level (`logger.logLevel` property)
190-
- logging metadata (`logger[metadataKey:]` and `logger.metadata`)
191-
192-
For the system to work, however, it is important that `LogHandler` treat the configuration as _value types_. This means that `LogHandler`s should be `struct`s and a change in log level or logging metadata should only affect the very `LogHandler` it was changed on.
193-
194-
However, in special cases, it is acceptable that a `LogHandler` provides some global log level override that may affect all `LogHandler`s created.
195-
196-
##### Emitting
197-
- emitting the log message itself
198-
199-
### Not under control of `LogHandler`s
200-
201-
`LogHandler`s do not control if a message should be logged or not. `Logger` will only invoke the `log` function of a `LogHandler` if `Logger` determines that a log message should be emitted given the configured log level.
202-
203-
## Source vs Label
204-
205-
A `Logger` carries an (immutable) `label` and each log message carries a `source` parameter (since SwiftLog 1.3.0). The `Logger`'s label
206-
identifies the creator of the `Logger`. If you are using structured logging by preserving metadata across multiple modules, the `Logger`'s
207-
`label` is not a good way to identify where a log message originated from as it identifies the creator of a `Logger` which is often passed
208-
around between libraries to preserve metadata and the like.
209-
210-
If you want to filter all log messages originating from a certain subsystem, filter by `source` which defaults to the module that is emitting the
211-
log message.
212-
213-
## Security
214-
215-
Please see [SECURITY.md](SECURITY.md) for SwiftLog's security process.
216-
217-
## Design
218-
219-
This logging API was designed with the contributors to the Swift on Server community and approved by the [SSWG (Swift Server Work Group)](https://swift.org/server/) to the 'sandbox level' of the SSWG's [incubation process](https://www.swift.org/sswg/incubation-process.html).
58+
## Available log handler backends
22059

221-
- [pitch](https://forums.swift.org/t/logging/16027), [discussion](https://forums.swift.org/t/discussion-server-logging-api/18834), [feedback](https://forums.swift.org/t/feedback-server-logging-api-with-revisions/19375)
222-
- [log levels](https://forums.swift.org/t/logging-levels-for-swifts-server-side-logging-apis-and-new-os-log-apis/20365)
60+
The community has built numerous specialized logging backends.
22361

224-
[api-docs]: https://apple.github.io/swift-log/docs/current/Logging/Structs/Logger.html
62+
A great way to discover available log backend implementations is searching the
63+
[Swift Package Index](https://swiftpackageindex.com/search?query=swift-log)
64+
for the `swift-log` keyword.

0 commit comments

Comments
 (0)