Skip to content
bennokressPublic

About

A small Swift Package that makes logging in the Xcode Console a little bit more beautiful

Resources

Stars

5 stars

Watchers

0 watching

Forks

Repository files navigation

Welcome to PrettyLog πŸ‘‹

Swift Package Index License

PrettyLog is a small Swift Package that makes logging in the Xcode Console a little bit more beautiful.

Installation

dependencies: [
    .package(url: "https://github.com/bennokress/PrettyLog", .upToNextMajor(from: "2.0.0"))
]

Requirements

  • Xcode 26 / Swift 6.2 toolchain or later (swift-tools-version: 6.2)
  • iOS 15, Mac Catalyst 15, macOS 12, tvOS 15 or watchOS 9 as deployment target

Migrating from an earlier version

Every major version comes with migration notes that list what changed and what you have to do:

Setup

PrettyLog ships no log target, no log levels, no log categories and no global log functions. Your app decides where its log statements go, which of those destinations may receive sensitive data, which levels it needs and how it titles its statements, so it defines all four once.

Every declaration in the samples below is marked nonisolated. New Xcode projects make the main actor the default isolation of an app (SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor). Without the keyword, your targets, levels, categories and log functions would belong to the main actor too, and logging from a background task, an actor or a nonisolated function would fail with errors like these:

  • Main actor-isolated global function 'logI(_:sensitiveMessages:joinedBy:category:)' cannot be called from outside of the actor
  • Main actor-isolated conformance of 'ConsoleLog' to 'LogTarget' cannot be used in nonisolated context
  • Main actor-isolated static property 'todo' can not be referenced from a nonisolated context

In a project without that setting the keyword changes nothing, so keep it either way.

1. Define a log target

A log target conforms to LogTarget and decides how a log statement looks and where it goes. This one prints to the Xcode console and only includes sensitive messages in debug builds:

import Foundation
import PrettyLog

nonisolated struct ConsoleLog: LogTarget {

    var canLogSensitiveInformation: Bool { isDebugApp }

    func createLog(_ level: LogLevel, message: String, category: LogCategory) {
        print("\(prefix(level: level, category: category)) \(message)")
    }

    // MARK: Private Helpers

    private var isDebugApp: Bool {
        #if DEBUG
        return true
        #else
        return false
        #endif
    }

    private var currentTimestamp: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm:ss.SSS"
        return formatter.string(from: Date())
    }

    private func prefix(level: LogLevel, category: LogCategory) -> String {
        "\(currentTimestamp) \(category.truncatedOrPadded(to: 20)) \(level.emoji)"
    }

}

LogTarget has three requirements:

  • canLogSensitiveInformation: if false, the target never receives the sensitive part of a log statement.
  • createLog(_:message:category:): builds the log statement and sends it to its destination.
  • logPriorityRange: the levels the target accepts. It is optional and allows every level by default.

2. Define your log levels

A log level is an emoji and a priority. Targets filter by priority, so give every level its own. This set is a good start:

import PrettyLog

nonisolated extension LogLevel {

    static var debug: LogLevel { LogLevel(emoji: "🟀", priority: 100) }
    static var verbose: LogLevel { LogLevel(emoji: "πŸ”΅", priority: 300) }
    static var info: LogLevel { LogLevel(emoji: "🟒", priority: 500) }
    static var warning: LogLevel { LogLevel(emoji: "🟑", priority: 700) }
    static var error: LogLevel { LogLevel(emoji: "πŸ”΄", priority: 900) }
    static var keyEvent: LogLevel { LogLevel(emoji: "πŸ“Š", priority: .max) }

}

The names are yours. If you would rather name the lower levels after where a statement should end up, see 'Semantic Log Levels'.

3. Define your log categories

A log category is a name that titles a log statement. The only one PrettyLog brings along is .uncategorized, the empty title of a statement without a category. This set is a good start:

import PrettyLog

nonisolated extension LogCategory {

    static var appState: LogCategory { LogCategory("App State") }
    static var debug: LogCategory { LogCategory("Debug") }
    static var general: LogCategory { LogCategory("General") }
    static var manager: LogCategory { LogCategory("Manager") }
    static var service: LogCategory { LogCategory("Service") }
    static var storage: LogCategory { LogCategory("Storage") }
    static var user: LogCategory { LogCategory("User Action") }
    static var view: LogCategory { LogCategory("View") }

}

4. Define your log functions

Create one Swift file in your app that imports PrettyLog, lists your targets and defines the global log functions you want to use. Every function hands its arguments on to PrettyLogProxy, because Swift can't forward variadic parameters from one function to another. With this file in place, no other file in your app needs to import PrettyLog.

import Foundation
import PrettyLog

/// Log a statement with DEBUG level.
/// - Parameters:
///   - messages: One or more strings and string-convertible objects to include in the log statement
///   - sensitiveMessages: One or more strings and string-convertible objects to include in the log statement if the target allows sensitive content
///   - separator: The separator between messages (defaults to `" - "`)
///   - category: The category of the log message (defaults to `.uncategorized`)
/// - Attention: No log will be created, if `messages` and `sensitiveMessages` are both empty or consist only of `nil`-elements!
nonisolated func logD(_ messages: String?..., sensitiveMessages: String?..., joinedBy separator: String = " - ", category: LogCategory = .uncategorized) {
    PrettyLogProxy.log(messages, sensitiveMessages: sensitiveMessages, joinedBy: separator, as: .debug, category: category, to: logTargets)
}

/// Log a statement with VERBOSE level.
/// - Parameters:
///   - messages: One or more strings and string-convertible objects to include in the log statement
///   - sensitiveMessages: One or more strings and string-convertible objects to include in the log statement if the target allows sensitive content
///   - separator: The separator between messages (defaults to `" - "`)
///   - category: The category of the log message (defaults to `.uncategorized`)
/// - Attention: No log will be created, if `messages` and `sensitiveMessages` are both empty or consist only of `nil`-elements!
nonisolated func logV(_ messages: String?..., sensitiveMessages: String?..., joinedBy separator: String = " - ", category: LogCategory = .uncategorized) {
    PrettyLogProxy.log(messages, sensitiveMessages: sensitiveMessages, joinedBy: separator, as: .verbose, category: category, to: logTargets)
}

/// Log a statement with INFO level.
/// - Parameters:
///   - messages: One or more strings and string-convertible objects to include in the log statement
///   - sensitiveMessages: One or more strings and string-convertible objects to include in the log statement if the target allows sensitive content
///   - separator: The separator between messages (defaults to `" - "`)
///   - category: The category of the log message (defaults to `.uncategorized`)
/// - Attention: No log will be created, if `messages` and `sensitiveMessages` are both empty or consist only of `nil`-elements!
nonisolated func logI(_ messages: String?..., sensitiveMessages: String?..., joinedBy separator: String = " - ", category: LogCategory = .uncategorized) {
    PrettyLogProxy.log(messages, sensitiveMessages: sensitiveMessages, joinedBy: separator, as: .info, category: category, to: logTargets)
}

/// Log a statement with WARNING level.
/// - Parameters:
///   - messages: One or more strings and string-convertible objects to include in the log statement
///   - sensitiveMessages: One or more strings and string-convertible objects to include in the log statement if the target allows sensitive content
///   - separator: The separator between messages (defaults to `" - "`)
///   - category: The category of the log message (defaults to `.uncategorized`)
/// - Attention: No log will be created, if `messages` and `sensitiveMessages` are both empty or consist only of `nil`-elements!
nonisolated func logW(_ messages: String?..., sensitiveMessages: String?..., joinedBy separator: String = " - ", category: LogCategory = .uncategorized) {
    PrettyLogProxy.log(messages, sensitiveMessages: sensitiveMessages, joinedBy: separator, as: .warning, category: category, to: logTargets)
}

/// Log a statement with ERROR level.
/// - Parameters:
///   - messages: One or more strings and string-convertible objects to include in the log statement
///   - sensitiveMessages: One or more strings and string-convertible objects to include in the log statement if the target allows sensitive content
///   - separator: The separator between messages (defaults to `" - "`)
///   - category: The category of the log message (defaults to `.uncategorized`)
/// - Attention: No log will be created, if `messages` and `sensitiveMessages` are both empty or consist only of `nil`-elements!
nonisolated func logE(_ messages: String?..., sensitiveMessages: String?..., joinedBy separator: String = " - ", category: LogCategory = .uncategorized) {
    PrettyLogProxy.log(messages, sensitiveMessages: sensitiveMessages, joinedBy: separator, as: .error, category: category, to: logTargets)
}

/// Log a Key Event.
/// - Parameters:
///   - messages: One or more strings and string-convertible objects to include in the log statement
///   - separator: The separator between messages (defaults to `" - "`)
///   - category: The category of the log message (defaults to `.uncategorized`)
/// - Attention: No log will be created, if `messages` is empty or consist only of `nil`-elements!
nonisolated func logK(_ messages: String?..., joinedBy separator: String = " - ", category: LogCategory = .uncategorized) {
    PrettyLogProxy.log(messages, joinedBy: separator, as: .keyEvent, category: category, to: logTargets)
}

/// Log an `Error`.
/// - Parameters:
///   - error: The error to log
///   - category: The category of the log message (defaults to `.uncategorized`)
/// - Attention: No log will be created, if `error` is `nil`.
nonisolated func log(_ error: Error?, category: LogCategory = .uncategorized) {
    PrettyLogProxy.log(error, as: .error, category: category, to: logTargets)
}

/// Log a `NSException`.
/// - Parameters:
///   - exception: The exception to log
///   - category: The category of the log statement (defaults to `.uncategorized`)
/// - Attention: No log will be created, if `exception` is `nil`.
nonisolated func log(_ exception: NSException?, category: LogCategory = .uncategorized) {
    PrettyLogProxy.log(exception, as: .error, category: category, to: logTargets)
}

// TODO: Add a log function for every other level you define -> for example `logT` for a level `.todo` (see "Custom Log Levels").

// MARK: - Log Targets

/// Every log statement is sent to these targets. Add your own, for example one that sends statements to your backend.
nonisolated private var logTargets: [LogTarget] {
    [ConsoleLog()]
}

Basic Usage

With the setup in place you can make your print statements prettier and more useful. Just replace this ...

print("User tapped Continue Button")

Console Output with default print statement

... with this:

logD("User tapped Continue Button")

Console Output with PrettyLog statement

So far so good. You have a lot more options with PrettyLog though ...

Advanced Usage

All samples below call the log functions from your own file (see 'Setup').

Log Levels

logD("A debug log")
logV("A verbose log")
logI("An info log")
logW("A warning log")
logE("An error log")

Console Output of multiple PrettyLog statements with different Log Levels

Semantic Log Levels

If your app has a staging environment, you may prefer to name the lower levels after where a statement should end up: Xcode, Staging and Production instead of Debug, Verbose and Info. Define them with the same values in place of debug, verbose and info, and use one set or the other, not both:

nonisolated extension LogLevel {

    static var xcode: LogLevel { LogLevel(emoji: "🟀", priority: 100) }
    static var staging: LogLevel { LogLevel(emoji: "πŸ”΅", priority: 300) }
    static var production: LogLevel { LogLevel(emoji: "🟒", priority: 500) }

}

Then name the log functions logX, logS and logP, passing as: .xcode, as: .staging and as: .production:

logX("A log only to Xcode")
logS("A log up to the Staging Environment")
logP("A log up to Production")

The Key Event from the setup is for statistics. It has the highest priority, so every target that filters by a minimum level receives it:

logK("And this is a Key Event Log for statistics")

Console Output of multiple PrettyLog statements using Semantic Log Levels

Log Categories

logV("Got an API Response ...", category: .service)
logV("Saving Token from API: \(token)", category: .storage)
logI("User tapped Continue Button", category: .user)
logE("Username and Password did not match", category: .manager)
logW("Or create a Category on the spot ...", category: LogCategory("Announcement"))

Console Output of multiple PrettyLog statements with different Log Categories

Sensitive Data Logging

But wouldn't it be nice to log that a token was saved in production, but omit the token itself there while still logging it in development? Pass it as a sensitive message. Only targets whose canLogSensitiveInformation is true receive it:

logV("Got an API Response ...", category: .service)
logI("Saving Token from API", sensitiveMessages: token, category: .storage)
logI("User tapped Continue Button", category: .user)
logE("Username and Password did not match", category: .manager)
logW("Or create a Category on the spot ...", category: LogCategory("Announcement"))

The same Log Statements as before, but the Token is now marked as sensitive data and can be sent to Production like that

Log Message Concatenation

logV(service, "Got an API Response ...", category: .service)
logW(screen, element, "Username too long", joinedBy: " β†’ ", category: .manager)

Console Output of multiple PrettyLog statements with different Log Categories

Errors and Exceptions

let error = NetworkError.notFound
let exception = NSException(name: .portTimeoutException, reason: nil)
log(error, category: .service)
log(exception, category: .service)

Console Output of PrettyLog statements that take in Error and NSException as arguments

Expert Usage

Custom Log Categories

The categories from the setup are only a suggestion. Add any category you need to the same extension:

nonisolated extension LogCategory {

    /// This category can be used like all the others: logV("Running Unit Tests ...", category: .todo)
    static var todo: LogCategory { LogCategory("To Do") }

}

A target can compare categories with ==, for example to send only .storage statements to a separate file.

Custom Log Levels

The levels from the setup are only a suggestion. Add any level you need to the same extension, with its own emoji and a priority that sorts it between the others:

nonisolated extension LogLevel {

    /// Sorts between `debug` and `verbose`.
    static var todo: LogLevel { LogLevel(emoji: "🟣", priority: 200) }

}

To use it like the other levels, define a global method like logT for it in your logging file (see 'Setup'):

/// Log messages in the provided order with TODO level
/// - Parameters:
///     - messages: One or more strings and string-convertible objects to include in the log statement
///     - sensitiveMessages: One or more strings and string-convertible objects to include in the log statement if the target allows sensitive content
///     - separator: The separator between messages (defaults to `" - "`)
/// - Attention: No log will be created, if `messages` and `sensitiveMessages` are both empty or consist only of `nil`-elements.
nonisolated func logT(_ messages: String?..., sensitiveMessages: String?..., joinedBy separator: String = " - ") {
    PrettyLogProxy.log(messages, sensitiveMessages: sensitiveMessages, joinedBy: separator, as: .todo, category: .todo, to: logTargets)
}

More Log Targets

In real world apps you might want to log to backends and web services as well, or locally with something other than print. Each destination is its own LogTarget, and your logging file sends every statement to all of them. A target for a backend would typically reject sensitive data and only accept the more important levels:

import Foundation
import PrettyLog

nonisolated struct BackendLog: LogTarget {

    let canLogSensitiveInformation = false

    var logPriorityRange: ClosedRange<LogLevel>? { .allowFrom(min: .info) }

    func createLog(_ level: LogLevel, message: String, category: LogCategory) {
        // Send the statement to your backend
    }

}

Then add it to the list in your logging file:

nonisolated private var logTargets: [LogTarget] {
    [ConsoleLog(), BackendLog()]
}

Keeping Targets in a Constant

LogTarget doesn't require Sendable, so a target can be any type, including a class with mutable state. The computed logTargets above creates the targets on every call and works with any of them. If you would rather create them once and keep them in a constant, the Swift 6 language mode requires the constant to be Sendable. Make your target types Sendable and declare the list like this:

nonisolated private let logTargets: [any LogTarget & Sendable] = [ConsoleLog(), BackendLog()]

Structs whose stored properties are all Sendable get the conformance automatically, as long as they aren't public. A class needs to be final and protect its mutable state itself, for example with a lock.

Author

πŸ‘¨πŸ»β€πŸ’» Benno Kress

🀝 Contributing

Contributions, issues and feature requests are welcome!
Feel free to check issues page.

πŸ“ License

Copyright Β© Benno Kress.
This project is MIT licensed.


This README was generated with ❀️ by readme-md-generator

About

A small Swift Package that makes logging in the Xcode Console a little bit more beautiful

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages