mirror of
https://github.com/apple/swift-log
synced 2026-11-25 03:57:48 +00:00
remove examples, add code of conduct, Swift 5
This commit is contained in:
1 parent
7db09d7d68
commit
6254844827
14 files changed
+61
-1089
No files matched your search
@@ -0,0 +1,55 @@
|
||||
# Code of Conduct
|
||||
To be a truly great community, SwiftNIO needs to welcome developers from all walks of life,
|
||||
with different backgrounds, and with a wide range of experience. A diverse and friendly
|
||||
community will have more great ideas, more unique perspectives, and produce more great
|
||||
code. We will work diligently to make the SwiftNIO community welcoming to everyone.
|
||||
|
||||
To give clarity of what is expected of our members, SwiftNIO has adopted the code of conduct
|
||||
defined by [contributor-covenant.org](https://www.contributor-covenant.org). This document is used across many open source
|
||||
communities, and we think it articulates our values well. The full text is copied below:
|
||||
|
||||
### Contributor Code of Conduct v1.3
|
||||
As contributors and maintainers of this project, and in the interest of fostering an open and
|
||||
welcoming community, we pledge to respect all people who contribute through reporting
|
||||
issues, posting feature requests, updating documentation, submitting pull requests or patches,
|
||||
and other activities.
|
||||
|
||||
We are committed to making participation in this project a harassment-free experience for
|
||||
everyone, regardless of level of experience, gender, gender identity and expression, sexual
|
||||
orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or
|
||||
nationality.
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
- The use of sexualized language or imagery
|
||||
- Personal attacks
|
||||
- Trolling or insulting/derogatory comments
|
||||
- Public or private harassment
|
||||
- Publishing other’s private information, such as physical or electronic addresses, without explicit permission
|
||||
- Other unethical or unprofessional conduct
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or reject comments,
|
||||
commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of
|
||||
Conduct, or to ban temporarily or permanently any contributor for other behaviors that they
|
||||
deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
By adopting this Code of Conduct, project maintainers commit themselves to fairly and
|
||||
consistently applying these principles to every aspect of managing this project. Project
|
||||
maintainers who do not follow or enforce the Code of Conduct may be permanently removed
|
||||
from the project team.
|
||||
|
||||
This code of conduct applies both within project spaces and in public spaces when an
|
||||
individual is representing the project or its community.
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by
|
||||
contacting a project maintainer at [swift-nio-conduct@group.apple.com](mailto:swift-nio-conduct@group.apple.com). All complaints will be reviewed and
|
||||
investigated and will result in a response that is deemed necessary and appropriate to the
|
||||
circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter
|
||||
of an incident.
|
||||
|
||||
*This policy is adapted from the Contributor Code of Conduct [version 1.3.0](https://contributor-covenant.org/version/1/3/0/).*
|
||||
|
||||
### Reporting
|
||||
A working group of community members is committed to promptly addressing any [reported issues](mailto:swift-nio-conduct@group.apple.com).
|
||||
Working group members are volunteers appointed by the project lead, with a
|
||||
preference for individuals with varied backgrounds and perspectives. Membership is expected
|
||||
to change regularly, and may grow or shrink.
|
||||
+1
-9
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:4.2
|
||||
// swift-tools-version:5.0
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
@@ -25,14 +25,6 @@ let package = Package(
|
||||
name: "Logging",
|
||||
dependencies: []
|
||||
),
|
||||
.target(
|
||||
name: "ExampleImplementation",
|
||||
dependencies: ["Logging"]
|
||||
),
|
||||
.target(
|
||||
name: "ExampleUsage",
|
||||
dependencies: ["Logging", "ExampleImplementation"]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LoggingTests",
|
||||
dependencies: ["Logging"]
|
||||
|
||||
@@ -1,292 +1,8 @@
|
||||
# swift-log
|
||||
|
||||
# Proposal Review: SSWG-0001 (Server Logging API)
|
||||
A Logging API package for Swift.
|
||||
|
||||
After the great [discussion thread](https://forums.swift.org/t/server-logging-api/18834), we are proposing this as a final revision of this proposal and enter the proposal review phase which will run until the 20th January 2019.
|
||||
## Design
|
||||
|
||||
We have integrated most of the feedback from the discussion thread so even if you have read the previous version, you will find some changes that you hopefully agree with. To highlight a few of the major changes:
|
||||
|
||||
- Logging metadata is now structures and now supports nested dictionaries and list values, in addition to strings of course.
|
||||
- only locally relevant metadata can now be passed to the individual log methods.
|
||||
- ship a multiplex logging solution with the API package
|
||||
|
||||
The feedback model will be very similar to the one known from Swift Evolution. The community is asked to provide feedback in the way outlined below and after the review period finishes, the SSWG will -- based on the community feedback -- decide whether to promote the proposal to the [Sandbox](https://github.com/swift-server/sswg/blob/master/process/incubation.md#process-diagram) maturity level or not.
|
||||
|
||||
### What goes into a review of a proposal?
|
||||
|
||||
The goal of the review process is to improve the proposal under review through constructive criticism and, eventually, determine the evolution of the server-side Swift ecosystem.
|
||||
|
||||
When reviewing a proposal, here are some questions to consider:
|
||||
|
||||
- What is your evaluation of the proposal?
|
||||
|
||||
- Is the problem being addressed significant enough?
|
||||
|
||||
- Does this proposal fit well with the feel and direction of Swift on Server?
|
||||
|
||||
- If you have used other languages or libraries with a similar feature, how do you feel that this proposal compares to those?
|
||||
|
||||
- How much effort did you put into your review? A glance, a quick reading, or an in-depth study?
|
||||
|
||||
Thank you for contributing to the Swift Server Work Group!
|
||||
|
||||
### What happens if the proposal gets accepted?
|
||||
|
||||
If this proposal gets accepted, the official repository will be created and the code (minus examples, the proposal text, etc) will be submitted. The repository will then become usable as a SwiftPM package and a version (likely `0.1.0`) will be tagged. The development (in form of pull requests) will continue as a regular open-source project.
|
||||
|
||||
---
|
||||
|
||||
# Server Logging API
|
||||
|
||||
* Proposal: SSWG-0001
|
||||
* Authors: [Johannes Weiss](https://github.com/weissi) & [Tomer Doron](https://github.com/tomerd)
|
||||
* Preferred initial maturity level: [Sandbox](https://github.com/swift-server/sswg/blob/master/process/incubation.md#process-diagram)
|
||||
* Name: `swift-server-logging-api`
|
||||
* Sponsor: Apple
|
||||
* Status: Active review (9th...20th January, 2019)
|
||||
* Implementation: [https://github.com/weissi/swift-server-logging-api-proposal](https://github.com/weissi/swift-server-logging-api-proposal), if accepted, a fresh repository will be created under github.com/apple
|
||||
* External dependencies: *none*
|
||||
* License: if accepted, it will be released under the [Apache 2](https://www.apache.org/licenses/LICENSE-2.0.html) license
|
||||
* Pitch: [Server: Pitches/Logging](https://forums.swift.org/t/logging/16027)
|
||||
* Description: A flexible API package that aims to become the standard logging API which Swift packages can use to log. The formatting and delivery/persistence of the log messages is handled by other packages and configurable by the individual applications without requiring users of the API package to change.
|
||||
|
||||
## Introduction
|
||||
|
||||
Almost all production server software needs logging that works with a variety of packages. So far, there have been a number of different ecosystems (e.g. Vapor, Kitura, Perfect, ...) that came up with their own solutions for logging, tracing, metrics, etc.
|
||||
|
||||
The SSWG however aims to provide a number of packages that can be shared across within the whole Swift on Server ecosystem so we need some amount of standardisation. Because different applications have different requirements on what logging should exactly do, we are proposing to establish a server-side Swift logging API that can be implemented by various logging backends (called `LogHandler`).
|
||||
`LogHandler`s are responsible to format the log messages and to deliver/persist them. The delivery might simply go to `stdout`, might be saved to disk or a database, or might be sent off to another machine to aggregate logs for multiple services. The implementation of concrete `LogHandler`s is out of scope of this proposal and also doesn't need to be standardised across all applications. What matters is a standard API libraries can use without needing to know where the log will end up eventually.
|
||||
|
||||
|
||||
## Motivation
|
||||
|
||||
As outlined above we should standardise on an API that if well adopted and applications should allow users to mix and match libraries from different vendors while still maintaining a consistent logging.
|
||||
The aim is to support all widely used logging models such as:
|
||||
|
||||
- one global logger, ie. one application-wise global that's always accessible
|
||||
- a scoped logger for example one per class/sub-system
|
||||
- a local logger that is always explicitly passed around where the logger itself can be a value type
|
||||
|
||||
There are also a number of features that most agreed we will need to support, most importantly:
|
||||
|
||||
- log levels
|
||||
- attaching structured metadata (such as a request ID) to the logger and individual log messages
|
||||
- being able to 'make up a logger out of thin air'; because we don't have one true way of dependency injection and it's better to log in a slightly different configuration than just reverting to `print(...)`
|
||||
|
||||
On top of the hard requirements the aim is to make the logging calls as fast as possible if nothing will be logged. If a log message is emitted, it will be mostly up to the `LogHandler`s to do so in a fast enough way. How fast 'fast enough' is depends on the requirements, some will optimise for never losing a log message and others might optimise for the lowest possible latency even if that might not guarantee log message delivery.
|
||||
|
||||
## Proposed solution
|
||||
|
||||
Overall, we propose three different core, top-level types:
|
||||
|
||||
1. `LogHandler`, a `protocol` which defines the interface a logging backend needs to implement in order to be compatible.
|
||||
2. `Logging`, the logging system itself, used to configure the `LogHandler` to be used as well as to retrieve a `Logger`.
|
||||
3. `Logger`, the core type which is used to log messages.
|
||||
|
||||
To get started with this API, a user only needs to become familiar with the `Logger` type which has a few straightforward methods that can be used to log messages as a certain log level, for example `logger.info("Hello world!")`. There's one step a user needs to perform before being able to log: The have to have a `Logger` instance. This instance can be either retrieved from the logging system itself using
|
||||
|
||||
```swift
|
||||
let logger = Logging.make("my-app")
|
||||
```
|
||||
|
||||
or through some different way provided by the framework they use or a more specialised logger package which might offer a global instance.
|
||||
|
||||
### The `Logger`
|
||||
|
||||
We propose one `struct Logger` which has a supports a number of different methods to possibly emit a log message. Namely `trace`, `debug`, `info`, `warning`, and `error`. To send a log a message you pick a log level and invoke the `Logger` method with the same name, for example
|
||||
|
||||
```swift
|
||||
logger.error("Houston, we've had a problem")
|
||||
```
|
||||
|
||||
We already briefly touched on this: Where do we get `logger: Logger` from? This question has two answers: Either the environment (could be a global variable, could be a function parameter, could be a class property, ...) provides `logger` or if not, it is always possible to obtain a logger from the logging system itself:
|
||||
|
||||
```swift
|
||||
let logger = Logging.make("com.example.app")
|
||||
logger.warning("uh oh, this is unexpected")
|
||||
```
|
||||
|
||||
To get the best logging experience and performance, it is advisable to use `.make` to pass `Logger`s around or store them in a global/instance variable rather than `.make`ing new `Logger`s whenever one needs to log a message.
|
||||
|
||||
## Detailed design
|
||||
|
||||
The full API of `Logger` is visible below except for one detail that is removed for readability: All the logging methods have parameters with default values indicating the file, function, and line of the log message.
|
||||
|
||||
```swift
|
||||
public struct Logger {
|
||||
public var logLevel: Logging.Level
|
||||
|
||||
public func log(level: Logging.Level, message: @autoclosure () -> String, metadata: @autoclosure () -> Logging.Metadata? = nil, error: Error? = nil)
|
||||
|
||||
public func trace(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logging.Metadata? = nil)
|
||||
|
||||
public func debug(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logging.Metadata? = nil)
|
||||
|
||||
public func info(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logging.Metadata? = nil)
|
||||
|
||||
public func warning(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logging.Metadata? = nil, error: Error? = nil)
|
||||
|
||||
public func error(_ message: @autoclosure () -> String, metadata: @autoclosure () -> Logging.Metadata? = nil, error: Error? = nil)
|
||||
|
||||
public subscript(metadataKey metadataKey: String) -> Logging.Metadata.Value? { get set }
|
||||
|
||||
public var metadata: Logging.Metadata? { get set }
|
||||
}
|
||||
```
|
||||
|
||||
The `logLevel` property as well as the `trace`, `debug`, `info`, `warning`, and `error` methods are probably self-explanatory. But the information that can be passed alongside a log message deserves some special mentions:
|
||||
|
||||
- `message`, a `String` that is the log message itself and the only required argument.
|
||||
- `metadata`, a dictionary of metadata information attached to only this log message. Please see below for a more detailed discussion of logging metadata.
|
||||
- `error`, an optional `Error` that can be sent along with `warning` and `error` messages indicating a possible error that led to this failure.
|
||||
|
||||
Both, `message` and `metadata` are `@autoclosure` parameters which means that if the message does not end up being logged (because it's below the currently configured log level) no unnecessary processing is done rendering the `String` or creating the metadata information.
|
||||
|
||||
Instead of picking one of the `trace`, `debug`, `info`, etc methods it is also possible to use the `log` method passing the desired log level as a parameter.
|
||||
|
||||
### Logging metadata
|
||||
|
||||
In production environments that are under heavy load it's often a great help (and many would say required) that certain metadata can be attached to every log message. Instead of seeing
|
||||
|
||||
```
|
||||
info: user 'Taylor' logged in
|
||||
info: user 'Swift' logged in
|
||||
warn: could not establish database connection: no route to host
|
||||
```
|
||||
|
||||
where it might be unclear if the warning message belong to the session with user 'Taylor' or user 'Swift' or maybe to none of the above, the following would be much clearer:
|
||||
|
||||
```
|
||||
info: user 'Taylor' logged in [request_UUID: 9D315532-FA5C-4E11-88E9-520C877F58B5]
|
||||
info: user 'Swift' logged in [request_UUID: 35CC2687-CD1E-45A3-80B7-CCCE278797E6]
|
||||
warn: could not establish database connection: no route to host [request_UUID: 9D315532-FA5C-4E11-88E9-520C877F58B5]
|
||||
```
|
||||
|
||||
now it's fairly straightforward to identify that the database issue was in the request where we were dealing with user 'Taylor' because the request ID matches. The question is: How can we decorate all our log messages with the 'request UUID' or other information that we may need to correlate the messages? The easy option is:
|
||||
|
||||
```swift
|
||||
log.info("user \(userID) logged in [request_UUID: \(currentRequestUUID)]")
|
||||
```
|
||||
|
||||
and similarly for all log messages. But it quickly becomes tedious appending `[request_UUID: \(currentRequestUUID)]` to every single log message. The other option is this:
|
||||
|
||||
```swift
|
||||
logger[metadataKey: "request_UUID"] = currentRequestUUID
|
||||
```
|
||||
|
||||
and from then on a simple
|
||||
|
||||
```swift
|
||||
logger.info("user \(userID) logged in")
|
||||
```
|
||||
|
||||
is enough because the logger has been decorated with the request UUID already and from now on carries this information around.
|
||||
|
||||
In other cases however, it might be useful to attach some metadata to only one message and that can be achieved by using the `metadata` parameter from above:
|
||||
|
||||
```swift
|
||||
logger.trace("user \(userID) logged in",
|
||||
metadata: ["extra_user_info": [ "favourite_colour": userFaveColour,
|
||||
"auth_method": "password" ]])
|
||||
```
|
||||
|
||||
The above invocation will log the message alongside metadata merged from the `logger`'s metadata and the metadata provided with the `logger.trace` call.
|
||||
|
||||
The logging metadata is of type `typealias Logging.Metadata = [String: Metadata.Value]` where `Metadata.Value` is the following `enum` allowing nested structures rather than just `String`s as values.
|
||||
|
||||
```swift
|
||||
public enum MetadataValue {
|
||||
case string(String)
|
||||
case stringConvertible(CustomStringConvertible)
|
||||
case dictionary(Metadata)
|
||||
case array([Metadata.Value])
|
||||
}
|
||||
```
|
||||
|
||||
Users usually don't need to interact with the `Metadata.Value` type directly as it conforms to the `ExpressibleByStringLiteral`, `ExpressibleByStringInterpolation`, `ExpressibleByDictionaryLiteral`, and `ExpressibleByArrayLiteral` protocols and can therefore be constructed using the string, array, and dictionary literals.
|
||||
|
||||
Examples:
|
||||
|
||||
```swift
|
||||
logger.info("you can attach strings, lists, and nested dictionaries",
|
||||
metadata: ["key_1": "and a string value",
|
||||
"key_2": ["and", "a", "list", "value"],
|
||||
"key_3": ["where": ["we": ["pretend", ["it": ["is", "all", "Objective C", "again"]]]]]])
|
||||
logger[metadataKey: "keys-are-strings"] = ["but", "values", ["are": "more"]]
|
||||
logger.warning("ok, we've seen enough now.")
|
||||
```
|
||||
|
||||
|
||||
### Custom `LogHandler`s
|
||||
|
||||
Just like metadata, custom `LogHandler`s are an advanced feature and users will typically just choose a pre-existing package that formats and persists/delivers the log messages in an appropriate way. Said that, the proposed package here is an API package and it will become much more useful if the community create a number of useful `LogHandler`s to say format the log messages with colour or ship them to Splunk/ELK.
|
||||
|
||||
We have already seen before that `Logging.make` is what gives us a fresh logger but that raises the question what kind of logging backend will I actually get when calling `Logging.make`? The answer: It's configurable _per application_. The application -- likely in its main function -- sets up the logging backend it wishes the whole application to use. Libraries should never change the logging implementation as that should owned by the application. Setting up the `LogHandler` to be used is straightforward:
|
||||
|
||||
```swift
|
||||
Logging.bootstrap(MyFavouriteLoggingImplementation.init)
|
||||
```
|
||||
|
||||
This instructs the `Logging` system to install `MyFavouriteLoggingImplementation` as the `LogHandler` to use. This should only be done once at the start of day and is usually left alone thereafter.
|
||||
|
||||
Next, we should discuss how one would implement `MyFavouriteLoggingImplementation`. It's enough to conform to the following protocol:
|
||||
|
||||
```swift
|
||||
public protocol LogHandler {
|
||||
func log(level: Logging.Level, message: String, metadata: Logging.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt)
|
||||
|
||||
subscript(metadataKey _: String) -> Logging.Metadata.Value? { get set }
|
||||
|
||||
var metadata: Logging.Metadata { get set }
|
||||
|
||||
var logLevel: Logging.Level { get set }
|
||||
}
|
||||
```
|
||||
|
||||
The implementation of the `log` function itself is rather straightforward: If `log` is invoked, `Logger` itself already decided that given the current `logLevel`, `message` should be logged. In other words, `LogHandler` does not even need to compare `level` to the currently configured level. That makes the shortest possible `LogHandler` implementation really quite short:
|
||||
|
||||
```swift
|
||||
public struct ShortestPossibleLogHandler: LogHandler {
|
||||
public var logLevel: Logging.Level = .info
|
||||
public var metadata: Logging.Metadata = [:]
|
||||
|
||||
public init(_ id: String) {}
|
||||
|
||||
public func log(level: Logging.Level, message: String, metadata: Logging.Metadata?, error: Error?, file: StaticString, function: StaticString, line: UInt) {
|
||||
print(message) // ignores all metadata, not recommended
|
||||
}
|
||||
|
||||
public subscript(metadataKey key: String) -> Metadata.Value? {
|
||||
get { return self.metadata[key] }
|
||||
set { self.metadata[key] = newValue }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
which can be installed using
|
||||
|
||||
```swift
|
||||
Logging.bootstrap(ShortestPossibleLogHandler.init)
|
||||
```
|
||||
|
||||
### Supported logging models
|
||||
|
||||
This API intends to support a number programming models:
|
||||
|
||||
1. Explicit logger passing, ie. handing loggers around as value-typed variables explicitly to everywhere log messages get emitted from.
|
||||
2. One global logger, ie. having one global that is _the_ logger.
|
||||
3. One logger per sub-system, ie. having a separate logger per sub-system which might be a file, a class, a module, etc.
|
||||
|
||||
Because there are fundamental differences with those models it is not mandated whether the `LogHandler` holds the logging configuration (log level and metadata) as a value or as a reference. Both systems make sense and it depends on the architecture of the application and the requirements to decide what is more appropriate.
|
||||
|
||||
Certain systems will also want to store the logging metadata in a thread/queue-local variable, some may even want try to automatically forward the metadata across thread switches together with the control flow. In the Java-world this model is called MDC, your mileage in Swift may vary and again hugely depends on the architecture of the system.
|
||||
|
||||
I believe designing a [MDC (mapped diagnostic context)](https://logback.qos.ch/manual/mdc.html) solution is out of scope for this proposal but the proposed API can work with such a system (see [examples](https://github.com/weissi/swift-server-logging-api-proposal/blob/50a8c8fdaceef62f1035d02ce0c8c5aa62252ff0/Tests/LoggingTests/MDCTest.swift)).
|
||||
|
||||
### Multiple log destinations
|
||||
|
||||
Finally, the API package will offer a solution to log to multiple `LogHandler`s at the same time through the `MultiplexLogging` facility. Let's assume you have two `LogHandler` implementations `MyConsoleLogger` & `MyFileLogger` and you wish to delegate the log messages to both of them, then the following one-time initialisation of the logging system will take care of this:
|
||||
|
||||
```swift
|
||||
let multiLogging = MultiplexLogging([MyConsoleLogger().make, MyFileLogger().make])
|
||||
Logging.bootstrap(multiLogging.make)
|
||||
```
|
||||
- [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)
|
||||
- [log levels](https://forums.swift.org/t/logging-levels-for-swifts-server-side-logging-apis-and-new-os-log-apis/20365)
|
||||
@@ -1,93 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER IMPLEMENTATION LOOKS LIKE
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
// helper class to keep things DRY
|
||||
internal struct CommonLogHandler {
|
||||
let label: String
|
||||
private var _logLevel: Logger.Level?
|
||||
private let formatter: DateFormatter
|
||||
private let lock = NSLock()
|
||||
|
||||
public init(label: String) {
|
||||
self.label = label
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
|
||||
formatter.locale = Locale(identifier: "en_US")
|
||||
formatter.calendar = Calendar(identifier: .gregorian)
|
||||
self.formatter = formatter
|
||||
}
|
||||
|
||||
public func log(level: Logger.Level, message: String, metadata: Logger.Metadata?, printer: (String) -> Void) {
|
||||
let prettyMetadata = metadata?.isEmpty ?? true ? self.prettyMetadata : self.prettify(self.metadata.merging(metadata!, uniquingKeysWith: { _, new in new }))
|
||||
printer("[\(self.label)] \(self.formatter.string(from: Date()))\(prettyMetadata.map { " \($0)" } ?? "") \(level): \(message)")
|
||||
}
|
||||
|
||||
public var logLevel: Logger.Level? {
|
||||
get {
|
||||
return self.lock.withLock { self._logLevel }
|
||||
}
|
||||
set {
|
||||
self.lock.withLock {
|
||||
self._logLevel = newValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var prettyMetadata: String?
|
||||
private var _metadata = Logger.Metadata() {
|
||||
didSet {
|
||||
self.prettyMetadata = self.prettify(self._metadata)
|
||||
}
|
||||
}
|
||||
|
||||
public var metadata: Logger.Metadata {
|
||||
get {
|
||||
return self.lock.withLock { self._metadata }
|
||||
}
|
||||
set {
|
||||
self.lock.withLock { self._metadata = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
|
||||
get {
|
||||
return self.lock.withLock { self._metadata[metadataKey] }
|
||||
}
|
||||
set {
|
||||
self.lock.withLock {
|
||||
self._metadata[metadataKey] = newValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func prettify(_ metadata: Logger.Metadata) -> String? {
|
||||
return !metadata.isEmpty ? metadata.map { "\($0)=\($1)" }.joined(separator: " ") : nil
|
||||
}
|
||||
}
|
||||
|
||||
private extension NSLock {
|
||||
func withLock<T>(_ body: () -> T) -> T {
|
||||
self.lock()
|
||||
defer {
|
||||
self.unlock()
|
||||
}
|
||||
return body()
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER IMPLEMENTATION LOOKS LIKE
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
// this is a contrived example of a logging library implementation that allows users to define log levels per logger label
|
||||
// this example uses a simplistic in-memory config which can be changed at runtime via code
|
||||
// real implementations could use external config files that can be changed outside the running program
|
||||
public class Config {
|
||||
private static let ALL = "*"
|
||||
|
||||
private let lock = NSLock()
|
||||
private var storage = [String: Logger.Level]()
|
||||
private var defaultLogLevel: Logger.Level
|
||||
|
||||
public init(defaultLogLevel: Logger.Level) {
|
||||
self.defaultLogLevel = defaultLogLevel
|
||||
}
|
||||
|
||||
func get(key: String) -> Logger.Level {
|
||||
return self.get(key) ?? self.get(Config.ALL) ?? self.defaultLogLevel
|
||||
}
|
||||
|
||||
func get(_ key: String) -> Logger.Level? {
|
||||
return self.lock.withLock { self.storage[key] }
|
||||
}
|
||||
|
||||
public func set(key: String, value: Logger.Level) {
|
||||
self.lock.withLock { self.storage[key] = value }
|
||||
}
|
||||
|
||||
public func set(value: Logger.Level) {
|
||||
self.lock.withLock { self.storage[Config.ALL] = value }
|
||||
}
|
||||
|
||||
public func clear() {
|
||||
self.lock.withLock { self.storage.removeAll() }
|
||||
}
|
||||
}
|
||||
|
||||
public struct ConfigLogHandler: LogHandler {
|
||||
private var handler: CommonLogHandler
|
||||
private var config: Config
|
||||
|
||||
public init(label: String, config: Config) {
|
||||
self.handler = CommonLogHandler(label: label)
|
||||
self.config = config
|
||||
}
|
||||
|
||||
public func log(level: Logger.Level, message: String, metadata: Logger.Metadata?, file: StaticString, function: StaticString, line: UInt) {
|
||||
self.handler.log(level: level, message: message, metadata: metadata) { text in
|
||||
print(text)
|
||||
}
|
||||
}
|
||||
|
||||
public var logLevel: Logger.Level {
|
||||
get { return self.handler.logLevel ?? self.config.get(key: self.handler.label) }
|
||||
set { self.handler.logLevel = newValue }
|
||||
}
|
||||
|
||||
public var metadata: Logger.Metadata {
|
||||
get { return self.handler.metadata }
|
||||
set { self.handler.metadata = newValue }
|
||||
}
|
||||
|
||||
public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
|
||||
get { return self.handler[metadataKey: metadataKey] }
|
||||
set { self.handler[metadataKey: metadataKey] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
private extension NSLock {
|
||||
func withLock<T>(_ body: () -> T) -> T {
|
||||
self.lock()
|
||||
defer {
|
||||
self.unlock()
|
||||
}
|
||||
return body()
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER IMPLEMENTATION LOOKS LIKE
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Logging
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
import Darwin
|
||||
#else
|
||||
import Glibc
|
||||
#endif
|
||||
|
||||
// this is a contrived example of a logging library implementation that writes logs to files
|
||||
public struct FileLogHandler: LogHandler {
|
||||
private var handler: CommonLogHandler
|
||||
private let defaultLogLevel: Logger.Level
|
||||
private let fileHandler = FileHandler()
|
||||
|
||||
public init(label: String) {
|
||||
self.init(label: label, defaultLogLevel: .info)
|
||||
}
|
||||
|
||||
public init(label: String, defaultLogLevel: Logger.Level) {
|
||||
self.handler = CommonLogHandler(label: label)
|
||||
self.defaultLogLevel = defaultLogLevel
|
||||
}
|
||||
|
||||
public func log(level: Logger.Level, message: String, metadata: Logger.Metadata?, file: StaticString, function: StaticString, line: UInt) {
|
||||
self.handler.log(level: level, message: message, metadata: metadata) { text in
|
||||
self.fileHandler._write(text)
|
||||
}
|
||||
}
|
||||
|
||||
public var logLevel: Logger.Level {
|
||||
get { return self.handler.logLevel ?? self.defaultLogLevel }
|
||||
set { self.handler.logLevel = newValue }
|
||||
}
|
||||
|
||||
public var metadata: Logger.Metadata {
|
||||
get { return self.handler.metadata }
|
||||
set { self.handler.metadata = newValue }
|
||||
}
|
||||
|
||||
public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
|
||||
get { return self.handler[metadataKey: metadataKey] }
|
||||
set { self.handler[metadataKey: metadataKey] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
private class FileHandler {
|
||||
let path: String
|
||||
let fd: Int32
|
||||
|
||||
init() {
|
||||
self.path = "/tmp/log-\(UUID().uuidString).txt"
|
||||
self.fd = open(self.path, O_WRONLY | O_CREAT | O_APPEND, 0o666)
|
||||
assert(self.fd > 0, "could not open \(self.path)")
|
||||
print("writing logs to \(self.path)")
|
||||
}
|
||||
|
||||
deinit {
|
||||
if fd > 0 {
|
||||
close(fd)
|
||||
}
|
||||
}
|
||||
|
||||
func _write(_ text: String) {
|
||||
write(self.fd, text + "\n", text.utf8.count + 1)
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER IMPLEMENTATION LOOKS LIKE
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
// this is a contrived example of a logging library implementation that writes logs to stdout
|
||||
public struct SimpleLogHandler: LogHandler {
|
||||
private var handler: CommonLogHandler
|
||||
private let defaultLogLevel: Logger.Level
|
||||
|
||||
public init(label: String) {
|
||||
self.init(label: label, defaultLogLevel: .info)
|
||||
}
|
||||
|
||||
public init(label: String, defaultLogLevel: Logger.Level) {
|
||||
self.handler = CommonLogHandler(label: label)
|
||||
self.defaultLogLevel = defaultLogLevel
|
||||
}
|
||||
|
||||
public func log(level: Logger.Level, message: String, metadata: Logger.Metadata?, file: StaticString, function: StaticString, line: UInt) {
|
||||
self.handler.log(level: level, message: message, metadata: metadata) { text in
|
||||
print(text)
|
||||
}
|
||||
}
|
||||
|
||||
public var logLevel: Logger.Level {
|
||||
get { return self.handler.logLevel ?? self.defaultLogLevel }
|
||||
set { self.handler.logLevel = newValue }
|
||||
}
|
||||
|
||||
public var metadata: Logger.Metadata {
|
||||
get { return self.handler.metadata }
|
||||
set { self.handler.metadata = newValue }
|
||||
}
|
||||
|
||||
public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
|
||||
get { return self.handler[metadataKey: metadataKey] }
|
||||
set { self.handler[metadataKey: metadataKey] = newValue }
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER USAGE LOOKS LIKE
|
||||
//
|
||||
|
||||
import ExampleImplementation
|
||||
import Foundation
|
||||
@testable import Logging // need access to internal bootstrap function
|
||||
|
||||
enum ConfigExample {
|
||||
static func main() {
|
||||
// boostrap with our config based sample implementations
|
||||
let config = Config(defaultLogLevel: .info)
|
||||
LoggingSystem.bootstrapInternal({ ConfigLogHandler(label: $0, config: config) })
|
||||
|
||||
// run the example
|
||||
let logger = Logger(label: "com.example.TestApp")
|
||||
logger.trace("hello world?")
|
||||
// changes the config in runtime, real implemnetations will use config files instead of in-memory config
|
||||
config.set(key: "com.example.TestApp", value: .trace)
|
||||
logger.trace("hello world!")
|
||||
}
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER USAGE LOOKS LIKE
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
// this is a contrived example of a context based system, ie a system that explictly passes a context object around
|
||||
// in this example we include a logger in the context object
|
||||
// we also allow users to set metadata on the context object and reuse that as the metadata for logging
|
||||
enum ContextBasedSystem {
|
||||
static func main() {
|
||||
// run the example
|
||||
for i in 1 ... 2 {
|
||||
print("---------------------------- processing request #\(i) ----------------------------")
|
||||
let context = Context(metadata: ["requestId": "\(UUID().uuidString)"]) // contrived context
|
||||
Foo().doSomething(context: context, requestNumnber: i)
|
||||
}
|
||||
}
|
||||
|
||||
struct Context {
|
||||
var logger = Logger(label: "ContextLogger")
|
||||
|
||||
init(metadata: Logger.Metadata = [:]) {
|
||||
metadata.forEach { self[$0.0] = $0.1 }
|
||||
}
|
||||
|
||||
// since logger is a value type, we can reuse our copy to manage the metadata
|
||||
subscript(metadataKey: String) -> Logger.Metadata.Value? {
|
||||
get { return self.logger[metadataKey: metadataKey] }
|
||||
set { self.logger[metadataKey: metadataKey] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
class Foo {
|
||||
func doSomething(context: Context, requestNumnber: Int) {
|
||||
var c = context // context is a value type, changes only effect this instance
|
||||
if 0 == requestNumnber % 2 {
|
||||
// debug verbosely every 2nd request
|
||||
c.logger.logLevel = .trace
|
||||
}
|
||||
c.logger.info("\(self)::doSomething")
|
||||
self.doSomethingElse(context: c)
|
||||
c.logger.info("\(self)::doSomething::end")
|
||||
}
|
||||
|
||||
private func doSomethingElse(context: Context) {
|
||||
var c = context // context is a value type, changes only effect this instance
|
||||
c["foo"] = "bar"
|
||||
c.logger.info("\(self)::doSomethingElse")
|
||||
c.logger.trace("\(self)::doSomethingElse:someDebugInfo")
|
||||
Bar().doSomething(context: c)
|
||||
c.logger.info("\(self)::doSomethingElse::end")
|
||||
}
|
||||
}
|
||||
|
||||
class Bar {
|
||||
func doSomething(context: Context) {
|
||||
var c = context // context is a value type, changes only effect this instance
|
||||
c["bar"] = "baz"
|
||||
c.logger.info("\(self)::doSomething")
|
||||
c.logger.trace("\(self)::doSomething:someDebugInfo")
|
||||
Baz().doSomething(context: c)
|
||||
c.logger.info("\(self)::doSomething::end")
|
||||
}
|
||||
}
|
||||
|
||||
class Baz {
|
||||
private let queue = DispatchQueue(label: "ContextBasedSystem::Baz")
|
||||
|
||||
func doSomething(context: Context) {
|
||||
context.logger.info("\(self)::doSomething")
|
||||
context.logger.trace("\(self)::doSomething:someDebugInfo")
|
||||
let group = DispatchGroup()
|
||||
group.enter()
|
||||
queue.async {
|
||||
context.logger.info("\(self)::doSomethingAsync")
|
||||
// since the library does not know about the context it will loose the metadata
|
||||
let library = RandomLibrary()
|
||||
library.doSomething()
|
||||
library.doSomethingAsync {
|
||||
group.leave()
|
||||
}
|
||||
}
|
||||
group.wait()
|
||||
|
||||
var l = context.logger // logger is a value type, changes only effect this instance
|
||||
l[metadataKey: "baz"] = "qux"
|
||||
l.info("\(self)::doSomething::Local")
|
||||
context.logger.info("\(self)::doSomething::end")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER USAGE LOOKS LIKE
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
// since this example mutates the global logger, we need to lock around it
|
||||
var _logger = Logger(label: "GlobalLogger")
|
||||
var lock = NSLock()
|
||||
var logger: Logger {
|
||||
get {
|
||||
return lock.withLock {
|
||||
_logger
|
||||
}
|
||||
}
|
||||
set {
|
||||
lock.withLock {
|
||||
_logger = newValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// this is a contrived example of a system that shares one global logger
|
||||
enum GlobalLoggerBasedSystem {
|
||||
static func main() {
|
||||
// run the example
|
||||
for i in 1 ... 2 {
|
||||
print("---------------------------- processing request #\(i) ----------------------------")
|
||||
logger[metadataKey: "requestId"] = "\(UUID().uuidString)"
|
||||
Foo().doSomething(requestNumnber: i)
|
||||
}
|
||||
}
|
||||
|
||||
class Foo {
|
||||
func doSomething(requestNumnber: Int) {
|
||||
if 0 == requestNumnber % 2 {
|
||||
// debug verbosely every 2nd request
|
||||
logger.logLevel = .trace
|
||||
}
|
||||
logger.info("\(self)::doSomething")
|
||||
self.doSomethingElse()
|
||||
logger.info("\(self)::doSomething::end")
|
||||
}
|
||||
|
||||
private func doSomethingElse() {
|
||||
logger[metadataKey: "foo"] = "bar"
|
||||
logger.info("\(self)::doSomethingElse")
|
||||
logger.trace("\(self)::doSomethingElse:someDebugInfo")
|
||||
Bar().doSomething()
|
||||
logger.info("\(self)::doSomethingElse::end")
|
||||
logger[metadataKey: "foo"] = nil
|
||||
}
|
||||
}
|
||||
|
||||
class Bar {
|
||||
func doSomething() {
|
||||
logger[metadataKey: "bar"] = "baz"
|
||||
logger.info("\(self)::doSomething")
|
||||
logger.trace("\(self)::doSomething:someDebugInfo")
|
||||
Baz().doSomething()
|
||||
logger.info("\(self)::doSomething::end")
|
||||
logger[metadataKey: "bar"] = nil
|
||||
}
|
||||
}
|
||||
|
||||
class Baz {
|
||||
private let queue = DispatchQueue(label: "GlobalLoggerBasedSystem::Baz")
|
||||
|
||||
func doSomething() {
|
||||
logger.info("\(self)::doSomething")
|
||||
logger.trace("\(self)::doSomething:someDebugInfo")
|
||||
let group = DispatchGroup()
|
||||
group.enter()
|
||||
queue.async {
|
||||
logger.info("\(self)::doSomethingAsync")
|
||||
// since the library does not know about the context it will loose the metadata
|
||||
let library = RandomLibrary()
|
||||
library.doSomething()
|
||||
library.doSomethingAsync {
|
||||
group.leave()
|
||||
}
|
||||
}
|
||||
group.wait()
|
||||
|
||||
var l = logger // logger is a value type, changes only effect this instance
|
||||
l[metadataKey: "baz"] = "qux"
|
||||
l.info("\(self)::doSomething::Local")
|
||||
logger.info("\(self)::doSomething::end")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension NSLock {
|
||||
func withLock<T>(_ body: () -> T) -> T {
|
||||
self.lock()
|
||||
defer {
|
||||
self.unlock()
|
||||
}
|
||||
return body()
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER USAGE LOOKS LIKE
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
// this is a contrived example of a system where each component obtain its own logger
|
||||
enum LocalLoggerBasedSystem {
|
||||
static func main() {
|
||||
// run the example
|
||||
for i in 1 ... 2 {
|
||||
print("---------------------------- processing request #\(i) ----------------------------")
|
||||
Foo().doSomething(requestNumnber: i)
|
||||
}
|
||||
}
|
||||
|
||||
class Foo {
|
||||
private var logger = Logger(label: "LocalLoggerBasedSystem::Foo")
|
||||
|
||||
func doSomething(requestNumnber: Int) {
|
||||
if 0 == requestNumnber % 2 {
|
||||
// debug verbosely every 2nd request
|
||||
self.logger.logLevel = .trace
|
||||
}
|
||||
self.logger.info("\(self)::doSomething")
|
||||
self.doSomethingElse(requestNumnber: requestNumnber)
|
||||
self.logger.info("\(self)::doSomething::end")
|
||||
}
|
||||
|
||||
private func doSomethingElse(requestNumnber: Int) {
|
||||
self.logger[metadataKey: "foo"] = "bar" // logger is a value type, changes only effect this instance
|
||||
self.logger.info("\(self)::doSomethingElse")
|
||||
self.logger.trace("\(self)::doSomethingElse:someDebugInfo")
|
||||
Bar().doSomething(requestNumnber: requestNumnber)
|
||||
self.logger.info("\(self)::doSomethingElse::end")
|
||||
}
|
||||
}
|
||||
|
||||
class Bar {
|
||||
private var logger = Logger(label: "LocalLoggerBasedSystem::Bar")
|
||||
|
||||
func doSomething(requestNumnber: Int) {
|
||||
if 0 == requestNumnber % 2 {
|
||||
// debug verbosely every 2nd request
|
||||
self.logger.logLevel = .trace
|
||||
}
|
||||
self.logger[metadataKey: "bar"] = "baz" // logger is a value type, changes only effect this instance
|
||||
self.logger.info("\(self)::doSomething")
|
||||
self.logger.trace("\(self)::doSomething:someDebugInfo")
|
||||
Baz().doSomething(requestNumnber: requestNumnber)
|
||||
self.logger.info("\(self)::doSomething::end")
|
||||
}
|
||||
}
|
||||
|
||||
class Baz {
|
||||
private var logger = Logger(label: "LocalLoggerBasedSystem::Baz")
|
||||
private let queue = DispatchQueue(label: "LocalLoggerBasedSystem::Baz")
|
||||
|
||||
func doSomething(requestNumnber: Int) {
|
||||
if 0 == requestNumnber % 2 {
|
||||
// debug verbosely every 2nd request
|
||||
self.logger.logLevel = .trace
|
||||
}
|
||||
self.logger.info("\(self)::doSomething")
|
||||
self.logger.trace("\(self)::doSomething:someDebugInfo")
|
||||
let group = DispatchGroup()
|
||||
group.enter()
|
||||
queue.async {
|
||||
self.logger.info("\(self)::doSomethingAsync")
|
||||
// since the library does not know about the context it will loose the metadata
|
||||
let library = RandomLibrary()
|
||||
library.doSomething()
|
||||
library.doSomethingAsync {
|
||||
group.leave()
|
||||
}
|
||||
}
|
||||
group.wait()
|
||||
|
||||
var l = logger // logger is a value type, changes only effect this instance
|
||||
l[metadataKey: "baz"] = "qux"
|
||||
l.info("\(self)::doSomething::Local")
|
||||
logger.info("\(self)::doSomething::end")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER USAGE LOOKS LIKE
|
||||
//
|
||||
|
||||
import ExampleImplementation
|
||||
import Foundation
|
||||
@testable import Logging // need access to internal bootstrap function
|
||||
|
||||
enum MultiplexExample {
|
||||
static func main() {
|
||||
// boostrap with two of our sample implementations
|
||||
LoggingSystem.bootstrapInternal({ MultiplexLogHandler([SimpleLogHandler(label: $0), FileLogHandler(label: $0)]) })
|
||||
|
||||
// run the example
|
||||
let logger = Logger(label: "com.example.TestApp")
|
||||
logger.info("hello world!")
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// THIS IS NOT PART OF THE PITCH, JUST AN EXAMPLE HOW A LOGGER USAGE LOOKS LIKE
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
// this is a contrived example of a 3rd party library that is used by the other examples
|
||||
// this library does not know anything about the systewm that used it, so cannot make
|
||||
// assumptions about them
|
||||
class RandomLibrary {
|
||||
private let logger = Logger(label: "RandomLibrary")
|
||||
private let queue = DispatchQueue(label: "RandomLibrary")
|
||||
|
||||
public init() {}
|
||||
|
||||
public func doSomething() {
|
||||
self.logger.info("doSomething")
|
||||
}
|
||||
|
||||
public func doSomethingAsync(completion: @escaping () -> Void) {
|
||||
self.queue.asyncAfter(deadline: .now() + 0.1) {
|
||||
self.logger.info("doSomethingAsync")
|
||||
completion()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Logging API open source project
|
||||
//
|
||||
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Logging
|
||||
import ExampleImplementation
|
||||
|
||||
// boostrap with our sample implementation
|
||||
LoggingSystem.bootstrap(SimpleLogHandler.init)
|
||||
|
||||
print()
|
||||
print("##### global logger based system #####")
|
||||
GlobalLoggerBasedSystem.main()
|
||||
|
||||
print()
|
||||
print("##### local logger based system #####")
|
||||
LocalLoggerBasedSystem.main()
|
||||
|
||||
print()
|
||||
print("##### context based system #####")
|
||||
ContextBasedSystem.main()
|
||||
|
||||
print()
|
||||
print("##### multiplexiing to multiple logging implementations #####")
|
||||
MultiplexExample.main()
|
||||
|
||||
print()
|
||||
print("##### config based logging implementations #####")
|
||||
ConfigExample.main()
|
||||
Reference in new issue
Block a user