Coder Social home page Coder Social logo

swift-log's Introduction

SwiftLog

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.

What SwiftLog provides today can be found in the API docs.

Getting started

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.

Adding the dependency

SwiftLog is designed for Swift 5. To depend on the logging API package, you need to declare your dependency in your Package.swift:

.package(url: "https://github.com/apple/swift-log.git", from: "1.0.0"),

and to your application/library target, add "Logging" to your dependencies, e.g. like this:

// Target syntax for Swift up to version 5.1
.target(name: "BestExampleApp", dependencies: ["Logging"]),

// Target for Swift 5.2
.target(name: "BestExampleApp", dependencies: [
    .product(name: "Logging", package: "swift-log")
],

Let's log

// 1) let's import the logging API package
import Logging

// 2) we need to create a logger, the label works similarly to a DispatchQueue label
let logger = Logger(label: "com.example.BestExampleApp.main")

// 3) we're now ready to use it
logger.info("Hello World!")

Output

2019-03-13T15:46:38+0000 info: Hello World!

Default Logger behavior

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:

LoggingSystem.bootstrap(StreamLogHandler.standardError)

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.

For further information, please check the API documentation.

Available Logging Backends For Applications

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:

Repository Handler Description
Kitura/HeliumLogger a logging backend widely used in the Kitura ecosystem
ianpartridge/swift-log-syslog a syslog backend
Adorkable/swift-log-format-and-pipe a backend that allows customization of the output format and the resulting destination
chrisaljoudi/swift-log-oslog an OSLog Unified Logging backend for use on Apple platforms. Important Note: we recommend using os_log directly as described here. 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, Making os_log accept string interpolations using compile-time interpretation.
Brainfinance/StackdriverLogging a structured JSON logging backend for use on Google Cloud Platform with the Stackdriver logging agent
DnV1eX/GoogleCloudLogging a client-side library for logging application events in Google Cloud via REST API v2.
vapor/console-kit a logger to the current terminal or stdout with stylized (ANSI) output. The default logger for all Vapor applications
neallester/swift-log-testing provides access to log messages for use in assertions (within test targets)
wlisac/swift-log-slack a logging backend that sends critical log messages to Slack
NSHipster/swift-log-github-actions a logging backend that translates logging messages into workflow commands for GitHub Actions.
stevapple/swift-log-telegram a logging backend that sends log messages to any Telegram chat (Inspired by and forked from wlisac/swift-log-slack)
jagreenwood/swift-log-datadog a logging backend which sends log messages to the Datadog log management service
google/SwiftLogFireCloud a logging backend for time series logging which pushes logs as flat files to Firebase Cloud Storage.
crspybits/swift-log-file a simple local file logger (using Foundation FileManager)
sushichop/Puppy a logging backend that supports multiple transports(console, file, syslog, etc.) and has the feature with formatting and file log rotation
luoxiu/LogDog user-friendly logging with sinks and appenders
ShivaHuang/swift-log-SwiftyBeaver a logging backend for printing colored logging to Xcode console / file, or sending encrypted logging to SwiftyBeaver platform.
Apodini/swift-log-elk a logging backend that formats, caches and sends log data to elastic/logstash
binaryscraping/swift-log-supabase a logging backend that sends log entries to Supabase.
kiliankoe/swift-log-matrix a logging backend for sending logs directly to a Matrix room
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.
CocoaLumberjack a fast & simple, yet powerful & flexible logging framework for macOS, iOS, tvOS and watchOS, which includes a logging backend for swift-log.
Your library? Get in touch!

What is an API package?

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.

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:

  1. a logging API
  2. a logging backend implementation

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.

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.

The core concepts

Loggers

Loggers 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:

// logging an informational message
logger.info("Hello World!")

// ouch, something went wrong
logger.error("Houston, we have a problem: \(problem)")

Log levels

The following log levels are supported:

  • trace
  • debug
  • info
  • notice
  • warning
  • error
  • critical

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.

Logging metadata

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:

var logger = logger
logger[metadataKey: "request-uuid"] = "\(UUID())"
logger.info("hello world")

will print

2019-03-13T18:30:02+0000 info: request-uuid=F8633013-3DD8-481C-9256-B296E43443ED hello world

with the default logging backend implementation that ships with SwiftLog. Needless to say, the format is fully defined by the logging backend you choose.

On the implementation of a logging backend (a LogHandler)

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.

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.

A LogHandler or logging backend implementation is anything that conforms to the following protocol

public protocol LogHandler {
    func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, source: String, file: String, function: String, line: UInt)

    subscript(metadataKey _: String) -> Logger.Metadata.Value? { get set }

    var metadata: Logger.Metadata { get set }

    var logLevel: Logger.Level { get set }
}

Instructing SwiftLog to use your logging backend as the one the whole application (including all libraries) should use is very simple:

LoggingSystem.bootstrap(MyLogHandler.init)

Implementation considerations

LogHandlers control most parts of the logging system:

Under control of a LogHandler

Configuration

LogHandlers control the two crucial pieces of Logger configuration, namely:

  • log level (logger.logLevel property)
  • logging metadata (logger[metadataKey:] and logger.metadata)

For the system to work, however, it is important that LogHandler treat the configuration as value types. This means that LogHandlers should be structs and a change in log level or logging metadata should only affect the very LogHandler it was changed on.

However, in special cases, it is acceptable that a LogHandler provides some global log level override that may affect all LogHandlers created.

Emitting
  • emitting the log message itself

Not under control of LogHandlers

LogHandlers 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.

Source vs Label

A Logger carries an (immutable) label and each log message carries a source parameter (since SwiftLog 1.3.0). The Logger's label identifies the creator of the Logger. If you are using structured logging by preserving metadata across multiple modules, the Logger's 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 around between libraries to preserve metadata and the like.

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 log message.

Security

Please see SECURITY.md for SwiftLog's security process.

Design

This logging API was designed with the contributors to the Swift on Server community and approved by the SSWG (Swift Server Work Group) to the 'sandbox level' of the SSWG's incubation process.

swift-log's People

Contributors

abdullahselek avatar adam-fowler avatar ahti avatar al45tair avatar compnerd avatar franzbusch avatar glbrntt avatar gwynne avatar ianpartridge avatar kevints avatar ktoso avatar luoxiu avatar mahdibm avatar mattt avatar maxdesiatov avatar mbarnach avatar natesg avatar neallester avatar philippzagar avatar ravikandhadai avatar rusik avatar shivahuang avatar slashmo avatar steipete avatar sushichop avatar tanner0101 avatar tkrajacic avatar tomerd avatar weissi avatar yim-lee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swift-log's Issues

StreamLogHandler is too quick to prettify metadata

I've noticed that StreamLogHandler prettifys meta data as soon as it is set.

This seems like it is probably wasteful.

  1. If you set multiple metadata keys (through subscript) it will re-prettify after each key.
  2. If you log with extra metadata the pre-prettified data can't be used.
  3. If you never log [at a level above the logLevel] the prettified data will never be used.

I propose that it would be better to prettify on first usage rather than when metadata is set.

The only downside I can think of is that this possibly shifts the prettification to a more critical moment in execution.

take out `metadata` to start with and make opaque later

On the forums , a few have rightly pointed out that currently, there's two places to get/set the metadata:

logger[metdataKey: "foo"] = "bar"

and

logger.metadata["foo"] = "bar"

The intention is to always use the former (logger[metdataKey: "foo"] = "bar") unless you want to store/retrieve the whole metadata storage, for example for MDC.

But as it was correctly pointed out, if that's the case we could/should make it opaque.

My proposal for right now is that the LogHandlers need to support both but the Logger should only expose the subscript. In a new minor version that we can release anytime, we could then add a back a well-designed story for MDC and friends.

Logging dynamic strings

logger.debug("My favourite number is \(someInt) and not \(someInt - 1)")

@weissi One somewhat subtle aspect of using custom string interpolation is that we cannot directly log a dynamic string right? E.g. if msg is of type String, we have to use logger.debug("\(msg)") to log it. Just wondering if adding a test case for this will help document this behavior.

StdoutLogHandler should be public

I'm looking at being an early adopter of SwiftLog because it looks good and I'm tired of solving the logging issue every time I start a new project. It occurs to me though, that StdoutLogHandler should be public but it is marked as internal.

The StdoutLogHandler is great because it provides out-of-the-box console logging to get up and moving fast and prevents the need to re-implement that, but being marked internal means that as soon as the use-case gets a little more interesting, I'd have to write my own console log handlers. The use case I'm referring to really just looks like this:

LoggingSystem.bootstrap {
  MultiplexLogHandler([StdoutLogHandler(label: $0), RemoteLogHandler(label: $0)])
}

I suppose MultiplexLogHandler could have some kind of configurability to implicitly create a StdoutLogHandler in addition to whichever log handlers are passed in. This could be an alternative to exposing StdoutLogHandler if that is truly the desire.

It's also worth pointing out that StdoutLogHandler's initializer is explicitly marked public. So I'm wondering if this has been an oversight.

I can open a PR to make a change if needed.

Feature Request: Varied Granularity Option for Multiplexed Loggers

Expected behavior

Currently MultiplexLogHandler mutates all registered handlers to the same log level; permitting fallthrough granularity would be useful for distributed systems.

Example:
1st Handler: logLevel: .trace ... // -> stdout pipe, local storage
2nd Handler: logLevel: .info ... // -> external endpoint, analytic processing backend
3rd Handler: logLevel: .critical .. // -> external endpoint, urgent sysadmin alert gateway

SwiftLog version/commit hash

swift-log 1.1.1

Lock is internal

I'd like to use Lock in a custom LogHandler implementation but am unable to because Lock is declared as internal in Locks.swift. Was Lock intended to be used like this?

Expected behavior

Under "Special cases" in the API docs here, the example implementation LogHandlerWithGlobalLogLevelOverride has a property overrideLock = Lock().

Actual behavior

This is not possible if the custom LogHandler implementation (e.g. LogHandlerWithGlobalLogLevelOverride) is defined in another module as Lock is internal and not visible there.

SwiftLog version/commit hash

version: 0.0.0

Swift & OS version (output of swift --version && uname -a)

Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1) Target: x86_64-apple-darwin18.6.0

Countdown to 1.0.0

I'm intending to cut 1.0.0 (and 0.1.0 for Swift 4.2 support) tonight 2019-04-09 (GMT).

The intended meaning of 1.0.0 is:

  • we now follow SemVer 2.0.0
  • you can now start depending on this package

and nothing else :)

Configuring log level

I am using Swift-Log initialized by LoggingSystem.bootstrap(StreamLogHandler.standardError), but on log messages with log level >= info are shown on the console window of XCode 12.0.1.
How can I configure the log level of the log messages shown on the console?
Thanks.

Will Logger.Message accept string interpolations?

extension Logger {
public struct Message: ExpressibleByStringLiteral, Equatable, CustomStringConvertible {
public typealias StringLiteralType = String
private var value: String
public init(stringLiteral value: String) {
self.value = value
}
public var description: String {
return self.value
}
}
}

@weissi Should Logger.Message conform to ExpressibleByStringInterpolation? I wonder if you can pass a string interpolation for logging with this definition?

Introduce #dsoHandle and args in addition to #file, #function and #line

Hello,

This is more like a pitch, not an issue at all, and itโ€™s probably too late. However, Iโ€™d like to have a custom handler for os_log, something like this works fine for debugging purposes, even though itโ€™s using private API:

import os
import _SwiftOSOverlayShims

...

func log(
  level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?,
  file: String, function: String, line: UInt, dso: UnsafeRawPointer, args: CVarArg...)
{
  let ra = _swift_os_log_return_address()
  message.withUTF8Buffer { (buf: UnsafeBufferPointer<UInt8>) in
    buf.baseAddress?.withMemoryRebound(to: CChar.self, capacity: buf.count) { str in
      withVaList(args) { valist in
        _swift_os_log(dso, ra, self.log_from_label(), self.type_from_level(level), message, valist)
      }
    }
  }
}

Unfortunately, the current log signature misses #dsoHandle and args, using #file, #function and #line instead. What do you think about adding two more arguments to the log function? Or maybe you have some alternative suggestion?

Thanks in advance!

Xcode 12 fails to compile with swift-log as a dependency

Expected behavior

When importing logging and using the a custom LogHandler, the app builds successfully

Actual behavior

Screen Shot 2020-06-22 at 4 33 17 PM

Steps to reproduce

  1. Create a protocol that uses Logger
  2. Example
public protocol LogListener {
    var isEnabled: Bool { get set }
    var logLevel: Logger.Level { get set }
    func logMessage(_ logDetails: ATHLogHandler.LogDetails)
}
  1. App Will fail to compile
  2. 'Logger' is ambiguous for type lookup in this context

SwiftLog version/commit hash

Version: 1.2.0

Swift & OS version (output of swift --version && uname -a)

Swift 5.3
macOS 11

Other Notes

I know this is on beta software and you're not required to support that anytime soon, but just wanted to put it out there.

Standards for using swift-log across multiple different packages

I have a question on standards of usage. When one is using swift-log across multiple different packages, should one use the same Logger instance across these packages or is it acceptable to use different instances? If using the same instance, is there a standard means to propagate that instance across packages? (e.g., some kind of dependency injection?).

Thanks,
Chris.

Enhancement: Logger that can be flushed? to better cooperate with CocoaLumberjack

I use Log and Logger API for general logging needs in my custom packages on Linux and iOS. Everything works great.

On iOS I initialize the Log.logger (for historical reasons and cooperation with legacy code) with my custom implementation of https://github.com/CocoaLumberjack/CocoaLumberjack based Logger implementation.

Also works great. Except for one thing. CocoaLumberjack is high perf and highly async, and when my app crashes controllably, the last few most important log statements are lost.

For that CocoaLumberjack provides a method DDLog.flushLog https://github.com/CocoaLumberjack/CocoaLumberjack/blob/832adf8139ee8b9810683a110a2318a9ea225a5a/Sources/CocoaLumberjack/include/CocoaLumberjack/DDLog.h#L367.

I would like to open a PR to propose addition of Logger.flush() and Log.flush() methods that would allow my app to invoke these methods and propagate them down in order to make sure logging is flushed in cases where app is terminated in a controlled manner.

What do you think? How you achieve the same?

bootstrapping in XCTestCase

LoggingSystem.bootstrap must only be called once per process. One might assume to bootstrap the logger in XCTestCase.setUp, but this can be called multiple times and will result in an assertion.

To get around this, a global lazy variable can be used that is asserted in each setUp method. It will only be run once, the first time it is accessed, allowing for logging to be configured in XCTests:

Declare the global variable like so:

let isLoggingConfigured: Bool = {
    LoggingSystem.bootstrap { label in
        var handler = StreamLogHandler.standardOutput(label: label)
        handler.logLevel = .debug
        return handler
    }
    return true
}()

Then, in your XCTestCases, use like so:

import XCTest

final class FooTests: XCTestCase {
    override func setUp() {
        XCTAssert(isLoggingConfigured)
        ...
    }
}

We should consider documenting this or providing some sort of helper.

The default "source" module determined by Logger/LogHandler is usually wrong

Expected behavior

Given this package layout:

.
|- Package.swift
 |- Sources
  |- ModuleA
   |- Subdir1
    |- Impl.swift
  |- ModuleB
   |- Subdir1
    |- Impl.swift

If I perform someLogger.info("hello") in ModuleA/Subdir1/Impl.swift and someLogger.info("world") in ModuleB/Subdir1/Impl.swift, I expect that the source parameters which reach the underlying LogHandler will be, respectively, ModuleA and ModuleB.

Actual behavior

In practice, the source parameter will be Subdir1 in both calls.

SwiftLog version/commit hash

SwiftLog 1.3.0

Swift & OS version (output of swift --version && uname -a)

Apple Swift version 5.3 (swiftlang-1200.0.16.9 clang-1200.0.22.5)
Target: x86_64-apple-darwin19.5.0
Darwin macbookpro.local 19.5.0 Darwin Kernel Version 19.5.0: Tue May 26 20:41:44 PDT 2020; root:xnu-6153.121.2~2/RELEASE_X86_64 x86_64

Further information

This is the natural result of using what is essentially basename(dirname(#file)) as the default for source in Logger.currentModule(filePath:) (

internal static func currentModule(filePath: String = #file) -> String {
) and Logger.log(level:_:metadata:source:file:function:line:) (
source: source() ?? Logger.currentModule(filePath: (file)),
). It assumes that all or most packages will use a flat structure for their source files beneath the "per-module" level. This is not the case for the vast majority of packages in, e.g., Vapor (see any of several repositories listed under https://github.com/vapor/ ), and in other common usage in large projects. Because this default is declared on Logger's log() method, it is difficult to override it via, for example, a project's choice of LogHandler, with the result that this new source parameter (otherwise a very useful input) must be ignored in favor of continuing to use such problematic solutions as parsing #file or #filePath (the irony that this behavior is also the cause of this very issue is not lost on me!).

Follow up: Showcase how a more complex logging backend library can bootstrap / keep its shared state

Title and end goal of ticket changed to add some examples, see discussion below for detail (edit: ktoso)


I was looking into creating a FileLogHandler but I am unsure of a safe and convenient way to go about doing that due to issues inherent with logging to files vs something like stdout with the current limitations of this framework.

For example, there is no available throwable factory overload and nowhere is it documented that a logger requires an initializer that takes a single String argument. Looking through the code it becomes much easier to see that you need some kind of an initializer that takes a single string argument. Why is there no official protocol requirement for the initializer if this is clearly a requirement?

I want to make a FileLogHandler, but with the current standard functionality, everyone would just be accustomed to passing in a label. I could just log in a common location like /var/log on linux, but people should be able to specify a custom file location if they so choose.

The Logger initializer that takes a LogHandler argument is internal so I cannot use that and the restrictions on the factory signature are too restrictive to allow this. I could make the String parameter the path to the log file, but since it is not throwable or nullable I cannot do any sort of validation that the path exists or is writable by the current process. Do I just silently fail? Should I just print a message?

Why are there no throwable/nullable overloads for the factory? or why is there no ability to use a custom factory signature? The fileprivate restrictions make it more difficult to provide my own handy extensions to achieve my desired functionality.

Is there something I'm missing here or was there just massive oversight when designing this? From what I can tell it would be extremely difficult to set up a logger that sends logs to an external service requiring connection parameters and there's no way you could validate those parameters during initialization of the handler.

Function parameter dropped in trace

Expected behavior

When I perform someLogger.trace("hello", function: "someFunction()") I expect that the function parameter that reaches the underlying LogHandler will be, someFunction().

Actual behavior

In practice, the function parameter will be trace(_:metadata:file:function:line:).

SwiftLog version/commit hash

SwiftLog 1.4.1

Swift & OS version (output of swift --version && uname -a)

Apple Swift version 5.3.2 (swiftlang-1200.0.45 clang-1200.0.32.28)
Target: x86_64-apple-darwin19.6.0
Darwin Sauls-MacBook-Pro-16-inch-2019 19.6.0 Darwin Kernel Version 19.6.0: Tue Jan 12 22:13:05 PST 2021; root:xnu-6153.141.16~1/RELEASE_X86_64 x86_64

Further information

When adding back the accidentally removed functions on #152, the source-less trace call doesn't pass the value of function when calling trace with the source parameter. As a result, the value of function is always trace(_:metadata:file:function:line:) for all calls to trace where a source is not set.

For reference: LoggerWithSource

PR #135 introduces a source parameter that defaults to the module in which a log statement was made.
See there for a long discussion why that matters -- long story short: it enables us to share a logger instance with an un-changing label, yet still keep the "this was logged from sub-component X (the module)".

We also considered adding a LoggerWithSource back then, however we decided that there are few use-cases about it today and we want to take it slow adding API. This ticket is to collect interest if this type should also ship with the swift-log library or not necessarily, as we learn about usage patterns.

The LoggerWithSource allows for overriding with a hardcoded source e.g. "thread-pool-x" or something the source of the log message. We concluded however that in most situations such things can be handled with metadata. If we see that overriding a source becomes

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2020 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
//
//===----------------------------------------------------------------------===//

/// `LoggerWithSource` shares the same API as `Logger`, except that it automatically parses on the supplies `source`
/// instead of requiring the user to supply source when logging a message.
///
/// - info: Do not accept or pass `LoggerWithSource` to/from other modules. The type you use publicly should always be
///         `Logger`.
public struct LoggerWithSource {
    /// The `Logger` we are logging with.
    public var logger: Logger

    /// The source information we are supplying to `Logger`.
    public var source: String

    /// Construct a `LoggerWithSource` logging with `logger` and `source`.
    @inlinable
    public init(_ logger: Logger, source: String) {
        self.logger = logger
        self.source = source
    }
}

extension LoggerWithSource {
    /// Log a message passing the log level as a parameter.
    ///
    /// If the `logLevel` passed to this method is more severe than the `Logger`'s `logLevel`, it will be logged,
    /// otherwise nothing will happen. The `source` is the one supplied to the initializer of `LoggerWithSource`.
    ///
    /// - parameters:
    ///    - level: The log level to log `message` at. For the available log levels, see `Logger.Level`.
    ///    - message: The message to be logged. `message` can be used with any string interpolation literal.
    ///    - metadata: One-off metadata to attach to this log message
    ///    - file: The file this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#file`).
    ///    - function: The function this log message originates from (there's usually no need to pass it explicitly as
    ///                it defaults to `#function`).
    ///    - line: The line this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#line`).
    @inlinable
    public func log(level: Logger.Level,
                    _ message: @autoclosure () -> Logger.Message,
                    metadata: @autoclosure () -> Logger.Metadata? = nil,
                    file: String = #file, function: String = #function, line: UInt = #line) {
        self.logger.log(level: level,
                        message(),
                        metadata: metadata(),
                        source: self.source,
                        file: file, function: function, line: line)
    }

    /// Add, change, or remove a logging metadata item.
    ///
    /// The `source` is the one supplied to the initializer of `LoggerWithSource`.
    ///
    /// - note: Logging metadata behaves as a value that means a change to the logging metadata will only affect the
    ///         very `Logger` it was changed on.
    @inlinable
    public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
        get {
            return self.logger[metadataKey: metadataKey]
        }
        set {
            self.logger[metadataKey: metadataKey] = newValue
        }
    }

    /// Get or set the log level configured for this `Logger`.
    ///
    ///  The `source` is the one supplied to the initializer of `LoggerWithSource`.
    ///
    /// - note: `Logger`s treat `logLevel` as a value. This means that a change in `logLevel` will only affect this
    ///         very `Logger`. It it acceptable for logging backends to have some form of global log level override
    ///         that affects multiple or even all loggers. This means a change in `logLevel` to one `Logger` might in
    ///         certain cases have no effect.
    @inlinable
    public var logLevel: Logger.Level {
        get {
            return self.logger.logLevel
        }
        set {
            self.logger.logLevel = newValue
        }
    }
}

extension LoggerWithSource {
    /// Log a message passing with the `Logger.Level.trace` log level.
    ///
    /// The `source` is the one supplied to the initializer of `LoggerWithSource`.
    ///
    /// If `.trace` is at least as severe as the `Logger`'s `logLevel`, it will be logged,
    /// otherwise nothing will happen.
    ///
    /// - parameters:
    ///    - message: The message to be logged. `message` can be used with any string interpolation literal.
    ///    - metadata: One-off metadata to attach to this log message
    ///    - file: The file this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#file`).
    ///    - function: The function this log message originates from (there's usually no need to pass it explicitly as
    ///                it defaults to `#function`).
    ///    - line: The line this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#line`).
    @inlinable
    public func trace(_ message: @autoclosure () -> Logger.Message,
                      metadata: @autoclosure () -> Logger.Metadata? = nil,
                      file: String = #file, function: String = #function, line: UInt = #line) {
        self.logger.trace(message(),
                          metadata: metadata(),
                          source: self.source,
                          file: file,
                          function: function,
                          line: line)
    }

    /// Log a message passing with the `Logger.Level.debug` log level.
    ///
    /// The `source` is the one supplied to the initializer of `LoggerWithSource`.
    ///
    /// If `.debug` is at least as severe as the `Logger`'s `logLevel`, it will be logged,
    /// otherwise nothing will happen.
    ///
    /// - parameters:
    ///    - message: The message to be logged. `message` can be used with any string interpolation literal.
    ///    - metadata: One-off metadata to attach to this log message
    ///    - file: The file this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#file`).
    ///    - function: The function this log message originates from (there's usually no need to pass it explicitly as
    ///                it defaults to `#function`).
    ///    - line: The line this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#line`).
    @inlinable
    public func debug(_ message: @autoclosure () -> Logger.Message,
                      metadata: @autoclosure () -> Logger.Metadata? = nil,
                      file: String = #file, function: String = #function, line: UInt = #line) {
        self.logger.debug(message(),
                          metadata: metadata(),
                          source: self.source,
                          file: file,
                          function: function,
                          line: line)
    }

    /// Log a message passing with the `Logger.Level.info` log level.
    ///
    /// The `source` is the one supplied to the initializer of `LoggerWithSource`.
    ///
    /// If `.info` is at least as severe as the `Logger`'s `logLevel`, it will be logged,
    /// otherwise nothing will happen.
    ///
    /// - parameters:
    ///    - message: The message to be logged. `message` can be used with any string interpolation literal.
    ///    - metadata: One-off metadata to attach to this log message
    ///    - file: The file this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#file`).
    ///    - function: The function this log message originates from (there's usually no need to pass it explicitly as
    ///                it defaults to `#function`).
    ///    - line: The line this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#line`).
    @inlinable
    public func info(_ message: @autoclosure () -> Logger.Message,
                     metadata: @autoclosure () -> Logger.Metadata? = nil,
                     file: String = #file, function: String = #function, line: UInt = #line) {
        self.logger.info(message(),
                         metadata: metadata(),
                         source: self.source,
                         file: file,
                         function: function,
                         line: line)
    }

    /// Log a message passing with the `Logger.Level.notice` log level.
    ///
    /// The `source` is the one supplied to the initializer of `LoggerWithSource`.
    ///
    /// If `.notice` is at least as severe as the `Logger`'s `logLevel`, it will be logged,
    /// otherwise nothing will happen.
    ///
    /// - parameters:
    ///    - message: The message to be logged. `message` can be used with any string interpolation literal.
    ///    - metadata: One-off metadata to attach to this log message
    ///    - file: The file this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#file`).
    ///    - function: The function this log message originates from (there's usually no need to pass it explicitly as
    ///                it defaults to `#function`).
    ///    - line: The line this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#line`).
    @inlinable
    public func notice(_ message: @autoclosure () -> Logger.Message,
                       metadata: @autoclosure () -> Logger.Metadata? = nil,
                       file: String = #file, function: String = #function, line: UInt = #line) {
        self.logger.notice(message(),
                           metadata: metadata(),
                           source: self.source,
                           file: file,
                           function: function,
                           line: line)
    }

    /// Log a message passing with the `Logger.Level.warning` log level.
    ///
    /// The `source` is the one supplied to the initializer of `LoggerWithSource`.
    ///
    /// If `.warning` is at least as severe as the `Logger`'s `logLevel`, it will be logged,
    /// otherwise nothing will happen.
    ///
    /// - parameters:
    ///    - message: The message to be logged. `message` can be used with any string interpolation literal.
    ///    - metadata: One-off metadata to attach to this log message
    ///    - file: The file this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#file`).
    ///    - function: The function this log message originates from (there's usually no need to pass it explicitly as
    ///                it defaults to `#function`).
    ///    - line: The line this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#line`).
    @inlinable
    public func warning(_ message: @autoclosure () -> Logger.Message,
                        metadata: @autoclosure () -> Logger.Metadata? = nil,
                        file: String = #file, function: String = #function, line: UInt = #line) {
        self.logger.warning(message(),
                            metadata: metadata(),
                            source: self.source,
                            file: file,
                            function: function,
                            line: line)
    }

    /// Log a message passing with the `Logger.Level.error` log level.
    ///
    /// The `source` is the one supplied to the initializer of `LoggerWithSource`.
    ///
    /// If `.error` is at least as severe as the `Logger`'s `logLevel`, it will be logged,
    /// otherwise nothing will happen.
    ///
    /// - parameters:
    ///    - message: The message to be logged. `message` can be used with any string interpolation literal.
    ///    - metadata: One-off metadata to attach to this log message
    ///    - file: The file this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#file`).
    ///    - function: The function this log message originates from (there's usually no need to pass it explicitly as
    ///                it defaults to `#function`).
    ///    - line: The line this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#line`).
    @inlinable
    public func error(_ message: @autoclosure () -> Logger.Message,
                      metadata: @autoclosure () -> Logger.Metadata? = nil,
                      file: String = #file, function: String = #function, line: UInt = #line) {
        self.logger.error(message(),
                          metadata: metadata(),
                          source: self.source,
                          file: file,
                          function: function,
                          line: line)
    }

    /// Log a message passing with the `Logger.Level.critical` log level.
    ///
    /// The `source` is the one supplied to the initializer of `LoggerWithSource`.
    ///
    /// `.critical` messages will always be logged.
    ///
    /// - parameters:
    ///    - message: The message to be logged. `message` can be used with any string interpolation literal.
    ///    - metadata: One-off metadata to attach to this log message
    ///    - file: The file this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#file`).
    ///    - function: The function this log message originates from (there's usually no need to pass it explicitly as
    ///                it defaults to `#function`).
    ///    - line: The line this log message originates from (there's usually no need to pass it explicitly as it
    ///            defaults to `#line`).
    @inlinable
    public func critical(_ message: @autoclosure () -> Logger.Message,
                         metadata: @autoclosure () -> Logger.Metadata? = nil,
                         file: String = #file, function: String = #function, line: UInt = #line) {
        self.logger.critical(message(),
                             metadata: metadata(),
                             source: self.source,
                             file: file,
                             function: function,
                             line: line)
    }
}
    func testAllLogLevelsWorkWithOldSchoolLogHandlerButSourceIsNotPropagated() {
        let testLogging = OldSchoolTestLogging()

        var logger = LoggerWithSource(Logger(label: "\(#function)",
                                             factory: testLogging.make),
                                      source: "my-fancy-source")
        logger.logLevel = .trace

        logger.trace("yes: trace")
        logger.debug("yes: debug")
        logger.info("yes: info")
        logger.notice("yes: notice")
        logger.warning("yes: warning")
        logger.error("yes: error")
        logger.critical("yes: critical")

        // Please note that the source is _not_ propagated (because the backend doesn't support it).
        testLogging.history.assertExist(level: .trace, message: "yes: trace", source: "no source")
        testLogging.history.assertExist(level: .debug, message: "yes: debug", source: "no source")
        testLogging.history.assertExist(level: .info, message: "yes: info", source: "no source")
        testLogging.history.assertExist(level: .notice, message: "yes: notice", source: "no source")
        testLogging.history.assertExist(level: .warning, message: "yes: warning", source: "no source")
        testLogging.history.assertExist(level: .error, message: "yes: error", source: "no source")
        testLogging.history.assertExist(level: .critical, message: "yes: critical", source: "no source")
    }

    func testAllLogLevelsWorkOnLoggerWithSource() {
        let testLogging = TestLogging()
        LoggingSystem.bootstrapInternal(testLogging.make)

        var logger = LoggerWithSource(Logger(label: "\(#function)"), source: "my-fancy-source")
        logger.logLevel = .trace

        logger.trace("yes: trace")
        logger.debug("yes: debug")
        logger.info("yes: info")
        logger.notice("yes: notice")
        logger.warning("yes: warning")
        logger.error("yes: error")
        logger.critical("yes: critical")

        testLogging.history.assertExist(level: .trace, message: "yes: trace", source: "my-fancy-source")
        testLogging.history.assertExist(level: .debug, message: "yes: debug", source: "my-fancy-source")
        testLogging.history.assertExist(level: .info, message: "yes: info", source: "my-fancy-source")
        testLogging.history.assertExist(level: .notice, message: "yes: notice", source: "my-fancy-source")
        testLogging.history.assertExist(level: .warning, message: "yes: warning", source: "my-fancy-source")
        testLogging.history.assertExist(level: .error, message: "yes: error", source: "my-fancy-source")
        testLogging.history.assertExist(level: .critical, message: "yes: critical", source: "my-fancy-source")
    }

    func testLoggerWithSource() {
        let testLogging = TestLogging()
        LoggingSystem.bootstrapInternal(testLogging.make)

        var logger = Logger(label: "\(#function)").withSource("source")
        logger.logLevel = .trace

        logger.critical("yes: critical")

        testLogging.history.assertExist(level: .critical, message: "yes: critical", source: "source")
    }

snippets above are from the impl by @weissi.

API break in #135 (1.3.0)

In spite of #135 (comment), I think the was API actually broken in #135:

This:

@inlinable
public func debug(_ message: @autoclosure () -> Logger.Message,
                  metadata: @autoclosure () -> Logger.Metadata? = nil,
                  file: String = #file, function: String = #function, line: UInt = #line) {
    ...
}

...is not the same as:

@inlinable
public func debug(_ message: @autoclosure () -> Logger.Message,
                  metadata: @autoclosure () -> Logger.Metadata? = nil,
                  source: @autoclosure () -> String? = nil,
                  file: String = #file, function: String = #function, line: UInt = #line) {
    ...
}

We need to retain the old function signatures in addition to the new ones and just forward the implementation from the old to the new.

Should StdoutLogHandler include label in log output?

Expected behavior

When logging using different loggers, e.g.:

let one = Logger(label: "one")
let two = Logger(label: "two")

I would expect the labels one and two to appear in log output.
This is not the case with the default StdoutLogHandler:

internal struct StdoutLogHandler: LogHandler {
    private let lock = Lock()

    public init(label: String) {} // does not store label

I know the StdOutLogHandler is meant to be super minimal but this seems more like an omission?

Actual behavior

Label is not included in log statements logged through to default std out handler.

LoggerMetadata values are restricted to Strings

public enum MetadataValue {
/// A metadata value which is a `String`.
case string(String)
/// A metadata value which is some `CustomStringConvertible`.
case stringConvertible(CustomStringConvertible)
/// A metadata value which is a dictionary from `String` to `Logger.MetadataValue`.
case dictionary(Metadata)
/// A metadata value which is an array of `Logger.MetadataValue`s.
case array([Metadata.Value])
}

Constraining the raw values of the Logger's metadata to strings is fine for syslog style log entries, but some logging platforms support metadata values constrained to more than just strings.

Notably, GCP Stackdriver logging with google-fluentd allows you to record your log entries as JSON, see:
https://cloud.google.com/logging/docs/agent/configuration#streaming_logs_from_additional_inputs

A log entry appended to a log file using this type of logging looks like '{"code": 1001, "message": "This is a log from the log file at test-structured-log.log", "isBool": true }'

For this to work as intended for this particular cases, the logger metadata values would need to properly translate to all json raw values, i.e null, bool, number and string.

As of right now, a LogHandler could certainly be created for GCP stackdriver JSON format logging with the raw values being restricted to String only, but that would be a subpar solution that stops the Stackdriver platform from reaching its full potential.

It seems like addressing this, if desired, would incur significant breaking changes to swift-log, but given that some server side framework like Vapor 4 are about to make swift-log defacto, I think it's worth giving a thought :)

Use StaticString for Parameter file and function

Abstract

The proposal from SSWG: Server Logging API suggest using String for parameters like #file and #function.

func log(level: Logger.Level,
             message: Logger.Message,
             metadata: Logger.Metadata?,
             file: String, function: String, line: UInt)

But is using StaticString a better design in practice?

Current Situation

Log functions take String for #file and #function. But some logging frameworks (backends) take StaticString for these parameters.

Problem

The main problem is String can not convert to StaticString, so for those frameworks take StaticString as parameters, there is no way to build a LogHandler for them.

The only workaround I found is discard these information. For those backends don't care about the #file or #function this will be fine, like swift-log-oslog.

However, the others will always get the #file and #function in LogHandler, not the actual place in the program. This will be a big problem.

Proposed Solution

If we changed the parameter type from String to StaticString, those backends require StaticString can take it without problems. And those require String can easily convert it to what they want. A simple extension can do the trick.

extension StaticString {
    @inlinable
    var stringValue: String {
        self.withUTF8Buffer { String(decoding: $0, as: UTF8.self) }
    }
}

The cons of this change is, it breaks the API compatibility, log handler providers need to update their code for this chage.

Any suggestions about this idea?

MacCatalyst support

I experience a Catalyst problem - is there a solution or workaround?

Expected behavior

I expected the library to work also in a combined iOS/macOS project (Catalyst).

Actual behavior

I created a lightweight wrapper around the lib and put it into a "Log" Swift Package.
For "import Logging", the compiler tells:
"Logging is not available when building for Mac Catalyst. Consider using #if !targetEnvironment(macCatalyst) to conditionally import this framework."

SwiftLog version/commit hash

The Package.swift content for the Log wrapper:

import PackageDescription

let package = Package(
    name: "Log",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "Log",
            targets: ["Log"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
		.package(url: "https://github.com/apple/swift-log.git", from: "1.0.0"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "Log",
            dependencies: []),
        .testTarget(
            name: "LogTests",
            dependencies: ["Log"]),
    ]
)

Swift & OS version (output of swift --version && uname -a)

Xcode 11.0 (11A419c) / Swift 5 / macOS 10.15 / iOS 13.0

Align .bootstrap() style between SwiftLog and SwiftMetrics

The two recently accepted by the SSWG API packages both use the "bootstrap at system start style" to select a (logger | metrics) backend.

The Logging API requires:

LoggingSystem.bootstrap(MyLogHandler.init)

so exposing the LogHandler directly.

At the same time we say that "log handler is internal detail, don't worry about it."

The style is similar yet notably different in the metrics API:

MetricsSystem.bootstrap(SelectedMetricsImplementation())

as the SelectedMetricsImplementation often may / will contain more state than only being a function that creates a stateless metric.

Note as well that one can obtain the factory like MetricsSystem.factory which is important in order to implement more advanced features e.g. removing metrics.


I would like to propose re-aligning the style of how one performs bootstrap in both those APIs, so the SSWG APIs have a shared "feel" and meaning to words used -- e.g. that *Handler should never really appear in "user land" unless there is good reasons to.

Proposal:

  • adopt the style that SwiftMetrics have, so we'd bootstrap(SimpleLoggingFactory()) etc

Another point for this would be that I can definitely imagine using such factory to keep state around such as connections etc, if the logger wanted to send metrics to an external service for gathering etc.

WDYT?

Properly maintain milestones

Expected behavior

Milestones should be in sync with released versions.

Actual behavior

We released https://github.com/apple/swift-log/releases 1.1.1 but no such milestone exists.

1.1.0 exist and is not closed. etc.

Proposal

When closing tickets, always assign a milestone;
When releasing a version, ensure tickets or PRs if no ticket present for PR are assigned to milestone; Close milestone, link to it from release notes.

I think it matters a lot to be clean and consistent here.

We should start with cleaning up the existing issues / releases.
I can take this on.

WDYT @tomerd @weissi

A note for the readme

Expected behavior

package working as a dependency in swift 5.2

Actual behavior

You get this error:
dependency 'Logging' in target 'BestExampleApp' requires explicit declaration; reference the package in the target dependency with '.product(name: "Logging", package: "swift-log")'

Steps to reproduce

Following the README doesn't quite work. as the error says, you have to put the package name in with swift 5.2 so from the readme this section would change:

.target(name: "BestExampleApp", dependencies: ["Logging"]),

^^^ fails, so should become vvv

.target(name: "BestExampleApp", dependencies: [.product(name: "Logging", package: "swift-log")]),

add color feature?

Long long ago, Xcode console was colorful by plug-ins.
colorful console
Now Xcode not support it, we use ANSI format and other software to look up the log like terminal. detail

it's time to change it
best wishes

iOS Compatibility issues

I recently adopted swift-log. Now pod lib lint is failing with the following error.

import Logging
           ^
    
    ** BUILD FAILED **
    
    
    The following build commands failed:
    	CompileSwift normal i386
    	CompileSwiftSources normal i386 com.apple.xcode.tools.swift.compiler
    (2 failures)

Is swift-log only for server-side use? I believe this should be available on all platforms where swift is available may be as part of core-libs.

SwiftLog version

1.1.0

Swift & OS version (output of swift --version && uname -a)

Apple Swift version 5.0.1 (swiftlang-1001.0.82.4 clang-1001.0.46.5)
Target: x86_64-apple-darwin18.6.0
Darwin Prafulls-MacBook-Pro.local 18.6.0 Darwin Kernel Version 18.6.0: Thu Apr 25 23:16:27 PDT 2019; root:xnu-4903.261.4~2/RELEASE_X86_64 x86_64

Grab log levels from environment (LOGLEVEL / LOGLEVEL_label)

It would be great if the default StreamLogHandler would honour LOGLEVEL environment variables.

To change the loglevel I currently have to do this dance, right?:

LoggingSystem.bootstrap { label in
  var handler = StreamLogHandler.standardOutput(label: label)
  handler.logLevel = .trace
  return handler
}

Because StreamLogHandler hardcodes its level to .info:

public var logLevel: Logger.Level = .info

It would be nice if that would at least default to the setting of the LOGLEVEL environment variable, ideally w/ supporting LOGLEVEL_$label as well.
Essentially:

public var logLevel: Logger.Level = {
  let env = ProcessInfo.processInfo.environment
  return Logger.Level(rawValue: "LOGLEVEL_" + label)
         ?? Logger.Level(rawValue: "LOGLEVEL")
         ?? .info
}()

Maybe w/ a little more caching.

Metadata storage type & enable MDC storage use cases

This is the "later" follow up ticket to the "take out metadata to start with and make opaque later #31".

One use case of being able to "take the entire metadata" is keeping around data that is set for the lifetime of a resource, so a library may want to "1) store it 2) run user code, allowing it to shadow or remove metadata etc 3) restore the metadata for the next invocation"

This pattern is sometimes useful, and would be nice if we could support it, esp since without a "give me the metadata" a framework can not implement this without knowing all the keys that it should keep+restore.

Example test:

    func testMDCStyleMetadata() {
        let testLogging = TestLogging()
        LoggingSystem.bootstrapInternal(testLogging.make)

        var logger = Logger(label: "\(#function)")
        logger[metadataKey: "always"] = "there"

        func userCode() {
            logger[metadataKey: "always"] = "other"
            logger.info("hello world!")

            testLogging.history.assertExist(level: .info, message: "hello world!", metadata: ["always": "other"])
        }

        let old = logger.metadata
        userCode()
        logger.metadata = old

        func userCode2() {
            logger.info("hello world!")
            testLogging.history.assertExist(level: .info, message: "hello world!", metadata: ["always": "there"])
        }
        userCode2()
    }

Slightly better default formatting for logs

I know that this opens the floodgates of expanding the formatting capabilities of the basic dumb "out of the box" log handler this package ships with... but how do we feel providing a little better experience?

This would make debugging using SwiftLog in packages such as RediStack much easier as it wouldn't necessitate creating a custom formatter or pulling in a dependency just for development

Desired output

2020-09-18T22:51:14-0700 trace RediStack.RedisConnection : connection created
    rdstk_conn_id=AF0DFDB1-1C6F-43A4-B8C1-6AA09E84C363
2020-09-18T22:51:14-0700 trace RediStack.RedisConnection : received subscribe request
    rdstk_conn_id=AF0DFDB1-1C6F-43A4-B8C1-6AA09E84C363
2020-09-18T22:51:14-0700 trace RediStack.RedisConnection : adding subscription
    rdstk_ps_target=Channels 'multi_channel_test'
    rdstk_conn_id=AF0DFDB1-1C6F-43A4-B8C1-6AA09E84C363
2020-09-18T22:51:14-0700 debug RediStack.RedisConnection : not in pubsub mode, moving to pubsub mode
    rdstk_conn_id=AF0DFDB1-1C6F-43A4-B8C1-6AA09E84C363
2020-09-18T22:51:14-0700 trace RediStack.RedisConnection : handler added, adding subscription
    rdstk_conn_id=AF0DFDB1-1C6F-43A4-B8C1-6AA09E84C363
2020-09-18T22:51:14-0700 trace RediStack.RedisConnection : successfully entered pubsub mode
    rdstk_conn_id=AF0DFDB1-1C6F-43A4-B8C1-6AA09E84C363 

Current output

2020-09-18T22:51:14-0700 trace RediStack.RedisConnection : rdstk_conn_id=AF0DFDB1-1C6F-43A4-B8C1-6AA09E84C363 connection created
2020-09-18T22:51:14-0700 trace RediStack.RedisConnection : rdstk_conn_id=AF0DFDB1-1C6F-43A4-B8C1-6AA09E84C363 received subscribe request
2020-09-18T22:51:14-0700 trace RediStack.RedisConnection : rdstk_ps_target=Channels 'multi_channel_test' rdstk_conn_id=AF0DFDB1-1C6F-43A4-B8C1-6AA09E84C363 adding subscription
2020-09-18T22:51:14-0700 debug RediStack.RedisConnection : rdstk_conn_id=AF0DFDB1-1C6F-43A4-B8C1-6AA09E84C363 not in pubsub mode, moving to pubsub mode
2020-09-18T22:51:14-0700 trace RediStack.RedisConnection : rdstk_conn_id=AF0DFDB1-1C6F-43A4-B8C1-6AA09E84C363 handler added, adding subscription
2020-09-18T22:51:14-0700 trace RediStack.RedisConnection : rdstk_conn_id=AF0DFDB1-1C6F-43A4-B8C1-6AA09E84C363 successfully entered pubsub mode

Issue setting different levels on log handlers in a MultiplexLogHandler

Expected behavior

I expected that by setting different levels on the different handlers each one would be respected.

Actual behavior

Looks like logs are being handled by both handlers only when the log function used is above the levels of both handlers.

Steps to reproduce

In the following code snippet, MyLogger sets its own log level to .info in its init call.

    let stdoutLogger: (String) -> StreamLogHandler = { label in
      var logger = StreamLogHandler.standardOutput(label: label)
      logger.logLevel = .trace
      return logger
    }
    LoggingSystem.bootstrap { label in
      return MultiplexLogHandler([MyLogger(), stdoutLogger(label)])
    }

    log.trace("Test Trace")
    log.info("Test Info")

The output in the debugger is only:

2020-06-25T13:48:21-0400 info: Test Info

SwiftLog version/commit hash

1.2.0

Swift & OS version (output of swift --version && uname -a)

Swift 5.2 on iOS 13.5.1

Unable to log stored string

When handling errors, I would like to be able to log error.localizedDescription.

Expected behavior

logger.error(_:) takes in the string and logs it

Actual behavior

Error:

Cannot convert value of type 'String' to expected argument type 'Logger.Message'

Steps to reproduce

  1. Create a throwing function
  2. Invoke throwing function
  3. Add generic catch block
  4. Try to invoke Logger.error(_:) with error.localizedDescription
  5. Observe

If possible, minimal yet complete reproducer code (or URL to code)

GH Link to line/project I was working on when I found out

SwiftLog version/commit hash

From Package.resolved:

"revision": "a64dd7dafc06bcecc43ec4dff0d71ef797247456"
"version": "1.0.0"

Swift & OS version (output of swift --version && uname -a)

Apple Swift version 5.0.1 (swiftlang-1001.0.82.4 clang-1001.0.46.5)
Target: x86_64-apple-darwin18.5.0
Darwin LotU-MacBook-Pro.local 18.5.0 Darwin Kernel Version 18.5.0: Mon Mar 11 20:40:32 PDT 2019; root:xnu-4903.251.3~3/RELEASE_X86_64 x86_64

Why docs don't mention iOS?

Hello!
I noticed that the framework can be used in iOS, from closed issues and from the fact that I was able to add the package in Xcode. Should the README be updated to reflect this functionality? Do other features need to be implemented before updating it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.