XCGLogger

repository·main·Indexed 26 days ago

https://github.com/davewoodcom/xcglogger

A debug logging module for Swift projects that provides enriched log messages including timestamps, function names, filenames, and line numbers. It supports multiple log destinations such as the Apple System Log and files, various severity levels from .verbose to .emergency, and advanced features like log file rotation, ANSI color formatting, and filtering by filename, tag, or developer.

Tokens
3.1K
Snippets
13
Records
18
Agent score
37%

What's inside XCGLogger

  1. Install XCGLogger via CocoaPods

    main

    Add the following lines to your Podfile. You can include the core framework or specific subspecs like UserInfoHelpers for experimental dictionary tagging support.

    source 'https://github.com/CocoaPods/Specs.git'
    platform :ios, '12.0'
    use_frameworks!
    
    pod 'XCGLogger', '~> 7.1.5'

    Then run pod install.

  2. Install XCGLogger via Carthage

    main

    Add the following line to your Cartfile:

    github "DaveWoodCom/XCGLogger" ~> 7.1.5

    Then run carthage update --no-use-binaries or carthage update.

    Note for Swift 5.0+ developers: You must add $(SRCROOT)/Carthage/Build/iOS/ObjcExceptionBridging.framework to your Input Files in the Copy Carthage Frameworks Build Phase.

    ```github "DaveWoodCom/XCGLogger" ~> 7.1.5```
  3. Initialize XCGLogger using a closure

    main

    To ensure all initialization is contained in one place, you can use a closure to initialize your logger. This creates the object lazily. To ensure the logger (and its app details) is created immediately at app launch, force its creation by adding let _ = log in your didFinishLaunching method.

    let log: XCGLogger = {
        let log = XCGLogger(identifier: "advancedLogger", includeDefaultDestinations: false)
        // Customize as needed
        return log
    }()
  4. Quick Start: Basic Usage of XCGLogger

    main

    To get started quickly:

    1. Setup Frameworks: Add XCGLogger.framework and ObjcExceptionBridging.framework to the Embedded Binaries section under the General tab of your target.
    2. Import: Add import XCGLogger to your source files.
    3. Initialize: Declare a global constant for the default instance (e.g., in AppDelegate).
    4. Configure: Call .setup() to define log levels and output destinations.

    Configuration Options for .setup():

    • level: The minimum log level to output to the console.
    • showThreadName: Boolean to show the thread name.
    • showLevel: Boolean to show the log level.
    • showFileNames: Boolean to show the filename.
    • showLineNumbers: Boolean to show the line number.
    • writeToFile: A String or URL for file logging. If provided, the file is cleared before use. Omit or set to nil for console-only logging.
    • fileLevel: The minimum log level for file output. Omit or set to nil to match the console level.
  5. Configure multiple log destinations

    main

    XCGLogger allows you to send log messages to various destinations like the Apple System Log, files, or third-party servers. You can create a logger with no default destinations and manually add specific destination objects. Each destination can have its own outputLevel and configuration options (e.g., showFunctionName, showLineNumber, showDate).

    Note: A destination object can only be added to one logger object; adding it to a second will remove it from the first.

    // Create a logger object with no destinations
    let log = XCGLogger(identifier: "advancedLogger", includeDefaultDestinations: false)
    
    // Create a destination for the system console log (via NSLog)
    let systemDestination = AppleSystemLogDestination(identifier: "advancedLogger.systemDestination")
    systemDestination.outputLevel = .debug
    systemDestination.showFunctionName = true
    
    // Add the destination to the logger
    log.add(destination: systemDestination)
    
    // Create a file log destination
    let fileDestination = FileDestination(writeToFile: "/path/to/file", identifier: "advancedLogger.fileDestination")
    fileDestination.logQueue = XCGLogger.logQueue
    log.add(destination: fileDestination)
    
    // Add basic app info, version info etc, to the start of the logs
    log.logAppDetails()
  6. Log various data types

    main

    XCGLogger supports logging strings and most other Swift types (Booleans, Points, Enums, Tuples, Dictionaries) using the standard log level methods.

    log.debug("Hi there!")
    log.debug(true)
    log.debug(CGPoint(x: 1.1, y: 2.2))
    log.debug(MyEnum.Option)
    log.debug((4, 2))
    log.debug(["Device": "iPhone", "Version": 7])
  7. Configure ANSI color formatting for file destinations

    main

    You can add color to FileDestination logs using ANSIColorLogFormatter. This allows you to view colorized logs in a terminal. You can customize the color and options (like .bold, .italic, .faint, .underline) for each log level.

    if let fileDestination: FileDestination = log.destination(withIdentifier: XCGLogger.Constants.fileDestinationIdentifier) as? FileDestination {
        let ansiColorLogFormatter: ANSIColorLogFormatter = ANSIColorLogFormatter()
        ansiColorLogFormatter.colorize(level: .verbose, with: .colorIndex(number: 244), options: [.faint])
        ansiColorLogFormatter.colorize(level: .debug, with: .black)
        ansiColorLogFormatter.colorize(level: .info, with: .blue, options: [.underline])
        ansiColorLogFormatter.colorize(level: .notice, with: .green, options: [.italic])
        ansiColorLogFormatter.colorize(level: .warning, with: .red, options: [.faint])
        ansiColorLogFormatter.colorize(level: .error, with: .red, options: [.bold])
        ansiColorLogFormatter.colorize(level: .severe, with: .white, on: .red)
        ansiColorLogFormatter.colorize(level: .alert, with: .white, on: .red, options: [.bold])
        ansiColorLogFormatter.colorize(level: .emergency, with: .white, on: .red, options: [.bold, .blink])
        fileDestination.formatters = [ansiColorLogFormatter]
    }
  8. Append to existing log files

    main

    When initializing a FileDestination, you can use the shouldAppend: parameter to prevent the logger from overwriting existing files. You can also use appendMarker: to insert a string (like a relaunch marker) at the start of the appended content. If appendMarker is nil, no marker is added.

    let fileDestination = FileDestination(writeToFile: "/path/to/file", identifier: "advancedLogger.fileDestination", shouldAppend: true, appendMarker: "-- Relauched App --")
  9. Selectively execute code during logging

    main

    To avoid the performance cost of building log messages that are currently suppressed by the log level, pass a closure to the log methods. The code inside the closure will only execute if the log level is active.

    If you want to execute code without generating a log line, use verboseExec, debugExec, infoExec, warningExec, errorExec, or severeExec and return nil from the closure.

    log.debug {
        var total = 0.0
        for receipt in receipts {
            total += receipt.total
        }
        return "Total of all receipts: \(total)"
    }