### Conditional Logger Setup Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Configure different logging levels and queues based on the build environment. ```Swift #if DEBUG log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true) #else log.setup(level: .severe, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true) if let consoleLog = log.logDestination(XCGLogger.Constants.baseConsoleDestinationIdentifier) as? ConsoleDestination { consoleLog.logQueue = XCGLogger.logQueue } #endif ``` -------------------------------- ### Quick Setup for Console and File Logging Source: https://context7.com/davewoodcom/xcglogger/llms.txt Configure XCGLogger for basic console and file logging with sensible defaults. Specify log levels and whether to include thread names, levels, file names, and line numbers. ```swift import XCGLogger // Use the default singleton instance let log = XCGLogger.default // Quick setup with console and optional file logging log.setup( level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: "/path/to/app.log", fileLevel: .info // Optional: different level for file ) // Start logging immediately log.debug("App launched successfully") // Output: 2024-01-15 10:30:45.123 [Debug] [AppDelegate.swift:25] application(_:didFinishLaunchingWithOptions:) > App launched successfully ``` -------------------------------- ### Configure XCGLogger Setup Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Configure the logger's options, including log level, thread name, level display, file names, line numbers, and file output. The `writeToFile:` parameter can be a String or URL and will be cleared if it exists. Set to nil to log to console only. `fileLevel:` can set a different log level for file output. ```Swift log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: "path/to/file", fileLevel: .debug) ``` -------------------------------- ### Configure CocoaPods Podfile Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Add these lines to your Podfile to install XCGLogger using CocoaPods. ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '12.0' use_frameworks! pod 'XCGLogger', '~> 7.1.5' ``` -------------------------------- ### Initialize XCGLogger Using A Closure Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Initialize XCGLogger lazily using a closure for centralized setup. Ensure the logger is created at app launch if needed. ```Swift let log: XCGLogger = { let log = XCGLogger(identifier: "advancedLogger", includeDefaultDestinations: false) // Customize as needed return log }() ``` -------------------------------- ### Automate Swift Versioning in Podfile Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Use this post_install hook to manage Swift version settings for pods automatically. ```ruby post_install do |installer| installer.pods_project.targets.each do |target| if ['SomeTarget-iOS', 'SomeTarget-watchOS'].include? "#{target}" print "Setting #{target}'s SWIFT_VERSION to 4.2\n" target.build_configurations.each do |config| config.build_settings['SWIFT_VERSION'] = '4.2' end else print "Setting #{target}'s SWIFT_VERSION to Undefined (Xcode will automatically resolve)\n" target.build_configurations.each do |config| config.build_settings.delete('SWIFT_VERSION') end end end print "Setting the default SWIFT_VERSION to 3.2\n" installer.pods_project.build_configurations.each do |config| config.build_settings['SWIFT_VERSION'] = '3.2' end end ``` -------------------------------- ### Initialize FileDestination with Append Mode Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Enable appending to an existing log file and specify a custom marker for new sessions. ```Swift let fileDestination = FileDestination(writeToFile: "/path/to/file", identifier: "advancedLogger.fileDestination", shouldAppend: true, appendMarker: "-- Relauched App --") ``` -------------------------------- ### Configure Alternate Build Configurations Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Use Swift build flags to toggle logging levels between debug and production environments. ```Swift #if DEBUG log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true) #else log.setup(level: .severe, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true) #endif ``` -------------------------------- ### Import XCGLogger Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Import the XCGLogger framework at the beginning of your Swift source file. ```Swift import XCGLogger ``` -------------------------------- ### Using All Available Log Levels Source: https://context7.com/davewoodcom/xcglogger/llms.txt Demonstrates the use of all nine log levels provided by XCGLogger, from verbose to emergency. Only messages at or above the configured `outputLevel` will be logged. ```swift import XCGLogger let log = XCGLogger.default log.outputLevel = .debug // All available log levels (lowest to highest) log.verbose("Detailed tracing information") log.debug("Debug information for developers") log.info("General information for power users") log.notice("Normal but significant conditions") log.warning("Warning conditions that may indicate problems") log.error("Error conditions that are recoverable") log.severe("Critical errors, app may crash") log.alert("Action must be taken immediately") log.emergency("System is unusable") // Only messages at or above outputLevel are logged log.outputLevel = .warning log.debug("This won't be logged") // Filtered out log.warning("This will be logged") // Outputs normally log.error("This will also be logged") ``` -------------------------------- ### Add Carthage Dependency Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Add this line to your Cartfile to integrate XCGLogger via Carthage. ```text github "DaveWoodCom/XCGLogger" ~> 7.1.5 ``` -------------------------------- ### Configure System and File Log Destinations Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Set up XCGLogger to send logs to both the Apple System Log and a file. Customize output levels and details for each destination. ```Swift let log = XCGLogger(identifier: "advancedLogger", includeDefaultDestinations: false) let systemDestination = AppleSystemLogDestination(identifier: "advancedLogger.systemDestination") systemDestination.outputLevel = .debug systemDestination.showLogIdentifier = false systemDestination.showFunctionName = true systemDestination.showThreadName = true systemDestination.showLevel = true systemDestination.showFileName = true systemDestination.showLineNumber = true systemDestination.showDate = true log.add(destination: systemDestination) let fileDestination = FileDestination(writeToFile: "/path/to/file", identifier: "advancedLogger.fileDestination") fileDestination.outputLevel = .debug fileDestination.showLogIdentifier = false fileDestination.showFunctionName = true fileDestination.showThreadName = true fileDestination.showLevel = true fileDestination.showFileName = true fileDestination.showLineNumber = true fileDestination.showDate = true fileDestination.logQueue = XCGLogger.logQueue log.add(destination: fileDestination) log.logAppDetails() ``` -------------------------------- ### Configure Auto-Rotating File Destination in Swift Source: https://context7.com/davewoodcom/xcglogger/llms.txt Sets up a file destination that automatically archives logs based on size or time constraints. Includes options for custom date formatting and manual rotation control. ```swift import XCGLogger let log = XCGLogger(identifier: "com.myapp.logger", includeDefaultDestinations: false) // Configure auto-rotating file destination let autoRotatingDestination = AutoRotatingFileDestination( writeToFile: "/path/to/logs/app.log", identifier: "autoRotatingFile", shouldAppend: true, appendMarker: "-- Session Started --", attributes: [.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], maxFileSize: 1_048_576, // 1 MB (default) maxTimeInterval: 600, // 10 minutes (default) targetMaxLogFiles: 10 // Keep 10 archived files (default) ) autoRotatingDestination.outputLevel = .debug autoRotatingDestination.logQueue = XCGLogger.logQueue // Background processing // Optional: Custom archive filename suffix format let customDateFormatter = DateFormatter() customDateFormatter.dateFormat = "_yyyy-MM-dd_HHmmss" autoRotatingDestination.archiveSuffixDateFormatter = customDateFormatter // Optional: Callback when rotation occurs autoRotatingDestination.autoRotationCompletion = { success in if success { print("Log file rotated successfully") } } log.add(destination: autoRotatingDestination) // Manual operations autoRotatingDestination.rotateFile() // Force rotation autoRotatingDestination.cleanUpLogFiles() // Remove excess archives autoRotatingDestination.purgeArchivedLogFiles() // Delete all archives // Get list of archived files let archivedFiles = autoRotatingDestination.archivedFileURLs() for fileURL in archivedFiles { print("Archived log: \(fileURL.path)") } ``` -------------------------------- ### Advanced Logger Configuration with Multiple Destinations Source: https://context7.com/davewoodcom/xcglogger/llms.txt Create a fully customized logger with multiple destinations, such as console and file, each with independent settings for output level, identifiers, and date display. ```swift import XCGLogger // Create a logger with no default destinations let log = XCGLogger(identifier: "com.myapp.logger", includeDefaultDestinations: false) // Create and configure console destination let consoleDestination = ConsoleDestination(identifier: "console") consoleDestination.outputLevel = .debug consoleDestination.showLogIdentifier = false consoleDestination.showFunctionName = true consoleDestination.showThreadName = true consoleDestination.showLevel = true consoleDestination.showFileName = true consoleDestination.showLineNumber = true consoleDestination.showDate = true // Create and configure file destination let fileDestination = FileDestination( writeToFile: "/path/to/app.log", identifier: "file", shouldAppend: true, appendMarker: "-- App Relaunched --" ) fileDestination.outputLevel = .info // Less verbose than console fileDestination.showLogIdentifier = true fileDestination.showFunctionName = true fileDestination.showThreadName = false fileDestination.showLevel = true fileDestination.showFileName = true fileDestination.showLineNumber = true fileDestination.showDate = true // Process file logging in background for better performance fileDestination.logQueue = XCGLogger.logQueue // Add destinations to logger log.add(destination: consoleDestination) log.add(destination: fileDestination) // Log app details at startup log.logAppDetails() // Use the configured logger log.debug("Detailed debug info - console only") log.info("User logged in - both console and file") ``` -------------------------------- ### Define Custom Developer Extensions Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Create extensions on the `Dev` struct to define project-specific developer identifiers for use in logging. ```Swift extension Dev { static let dave = Dev("dave") static let sabby = Dev("sabby") } ``` -------------------------------- ### Enable ANSI Color Formatting Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Apply ANSIColorLogFormatter to a FileDestination to enable terminal-based color coding for different log levels. ```Swift 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] } ``` -------------------------------- ### Include Logs by Filename Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md To include logs only from specific files, use the `includeFrom:` initializer of `FileNameFilter` or toggle the `inverse` property of an exclusion filter. ```Swift log.filters = [FileNameFilter(includeFrom: ["AppDelegate.swift"])] ``` -------------------------------- ### Define Custom Tag Extensions Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Create extensions on the `Tag` struct to define project-specific tags for easier use in logging. ```Swift extension Tag { static let sensitive = Tag("sensitive") static let ui = Tag("ui") static let data = Tag("data") } ``` -------------------------------- ### Log with Merged User Info Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Use the overloaded `|` operator to merge `Tag` and `Dev` objects into a `userInfo` dictionary for logging. This requires at least two objects to automatically convert to a dictionary. ```Swift log.debug("A tagged log message", userInfo: Dev.dave | Tag.sensitive) ``` -------------------------------- ### Configure Background Log Processing Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Assign a dispatch queue to a log destination to move processing off the main thread. ```Swift fileDestination.logQueue = XCGLogger.logQueue ``` ```Swift fileDestination.logQueue = DispatchQueue.global(qos: .background) ``` -------------------------------- ### Manage Log Destinations Dynamically Source: https://context7.com/davewoodcom/xcglogger/llms.txt Add, retrieve, remove, and modify log destinations at runtime. Ensure the correct identifier is used when accessing or removing destinations. ```swift import XCGLogger let log = XCGLogger.default // Add a new destination let customFileDestination = FileDestination( writeToFile: "/path/to/custom.log", identifier: "customFile" ) log.add(destination: customFileDestination) // Retrieve a destination by identifier if let consoleDestination = log.destination(withIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier) as? ConsoleDestination { consoleDestination.outputLevel = .warning // Modify existing destination } // Remove a destination log.remove(destinationWithIdentifier: "customFile") // Or remove by reference log.remove(destination: customFileDestination) // Check if logger is enabled for a level if log.isEnabledFor(level: .debug) { // Perform debug-only operations } // Replace default console with Apple System Log (NSLog) log.remove(destinationWithIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier) let systemLogDestination = AppleSystemLogDestination(identifier: XCGLogger.Constants.systemLogDestinationIdentifier) log.add(destination: systemLogDestination) ``` -------------------------------- ### Add Swift Package Manager Dependency Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Include this entry in your Package.swift dependencies array. ```swift .Package(url: "https://github.com/DaveWoodCom/XCGLogger.git", majorVersion: 7) ``` -------------------------------- ### Log Various Data Types Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Log different data types including booleans, structs, enums, tuples, and dictionaries. ```Swift 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]) ``` -------------------------------- ### Add Git Submodule Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Use this command to add XCGLogger as a git submodule in your repository. ```bash git submodule add https://github.com/DaveWoodCom/XCGLogger.git ``` -------------------------------- ### Log with Single Tag User Info Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md When logging with only a single tag or developer, access the `.dictionary` property of the `Tag` or `Dev` object to create a compatible `userInfo` dictionary. ```Swift userInfo: Tag("Blah").dictionary ``` -------------------------------- ### Configure Background Log Processing Source: https://context7.com/davewoodcom/xcglogger/llms.txt Set log destinations to process logs asynchronously using a specified dispatch queue for improved performance. Set `logQueue` to `nil` for synchronous processing. ```swift import XCGLogger let log = XCGLogger(identifier: "com.myapp.logger", includeDefaultDestinations: false) // Create destinations let consoleDestination = ConsoleDestination(identifier: "console") let fileDestination = FileDestination(writeToFile: "/path/to/app.log", identifier: "file") // Console logs synchronously for immediate feedback during debugging // File destination processes asynchronously for better performance fileDestination.logQueue = XCGLogger.logQueue // Or use a custom queue let customQueue = DispatchQueue(label: "com.myapp.logging", qos: .background) fileDestination.logQueue = customQueue log.add(destination: consoleDestination) log.add(destination: fileDestination) // Conditional background processing based on build configuration #if DEBUG // Synchronous logging in debug for immediate output fileDestination.logQueue = nil #else // Background logging in release for performance fileDestination.logQueue = XCGLogger.logQueue #endif // Flush pending logs (useful before app termination) fileDestination.flush { print("All logs written to disk") } ``` -------------------------------- ### Log Simple String Message Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Log a basic string message using the debug level. ```Swift log.debug("Hi there!") ``` -------------------------------- ### Configure Custom Date Formats Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Assign a custom DateFormatter to the logger to control the timestamp appearance in logs. ```Swift let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM/dd/yyyy hh:mma" dateFormatter.locale = Locale.current log.dateFormatter = dateFormatter ``` -------------------------------- ### Declare Default Logger Instance Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Declare a global constant for the default XCGLogger instance in your AppDelegate or a similar global file. ```Swift let log = XCGLogger.default ``` -------------------------------- ### Execute Code Blocks Conditionally Based on Log Level Source: https://context7.com/davewoodcom/xcglogger/llms.txt Run specific code blocks only when a certain log level is enabled, preventing unnecessary computation. This is useful for expensive operations or complex message generation. ```swift import XCGLogger let log = XCGLogger.default log.outputLevel = .debug // Execute expensive operations only when debug level is active log.debugExec { let expensiveData = generateDetailedDebugReport() print("Debug report: \(expensiveData)") } // Log with closure - message only built if level is enabled log.debug { let complexCalculation = performExpensiveCalculation() return "Calculation result: \(complexCalculation)" } // Level-specific execution methods log.verboseExec { /* Only runs at verbose level */ } log.debugExec { /* Only runs at debug or lower */ } log.infoExec { /* Only runs at info or lower */ } log.warningExec { /* Only runs at warning or lower */ } log.errorExec { /* Only runs at error or lower */ } log.severeExec { /* Only runs at severe or lower */ } // Using exec directly with any level log.exec(.warning) { notifyAdminOfWarningCondition() } // Returning nil from closure skips the log without output log.debug { guard shouldLogThisCondition else { return nil } return "Condition met, logging this message" } ``` -------------------------------- ### Apply Emoji Prefixes and Postfixes to Log Messages Source: https://context7.com/davewoodcom/xcglogger/llms.txt Add custom emoji prefixes and postfixes to log messages for different levels. This formatter can be applied globally to the logger or to specific destinations. ```swift import XCGLogger let log = XCGLogger.default // Create emoji formatter let emojiFormatter = PrePostFixLogFormatter() emojiFormatter.apply(prefix: "đŸ—¯ ", postfix: " đŸ—¯", to: .verbose) emojiFormatter.apply(prefix: "🔹 ", postfix: " 🔹", to: .debug) emojiFormatter.apply(prefix: "â„šī¸ ", postfix: " â„šī¸", to: .info) emojiFormatter.apply(prefix: "âœŗī¸ ", postfix: " âœŗī¸", to: .notice) emojiFormatter.apply(prefix: "âš ī¸ ", postfix: " âš ī¸", to: .warning) emojiFormatter.apply(prefix: "â€ŧī¸ ", postfix: " â€ŧī¸", to: .error) emojiFormatter.apply(prefix: "đŸ’Ŗ ", postfix: " đŸ’Ŗ", to: .severe) emojiFormatter.apply(prefix: "🛑 ", postfix: " 🛑", to: .alert) emojiFormatter.apply(prefix: "🚨 ", postfix: " 🚨", to: .emergency) // Apply formatter to logger (affects all destinations) log.formatters = [emojiFormatter] log.warning("Low memory warning") // Output: 2024-01-15 10:30:45.123 [Warning] [MemoryManager.swift:42] checkMemory() > âš ī¸ Low memory warning âš ī¸ // Apply to specific destination only if let consoleDestination = log.destination(withIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier) { consoleDestination.formatters = [emojiFormatter] } ``` -------------------------------- ### Customize Log Level Descriptions Source: https://context7.com/davewoodcom/xcglogger/llms.txt Override default log level labels globally or per destination. This affects how log levels are displayed in the output. ```swift import XCGLogger let log = XCGLogger.default // Custom level descriptions (affects all destinations) log.levelDescriptions[.verbose] = "TRACE" log.levelDescriptions[.debug] = "DEBUG" log.levelDescriptions[.info] = "INFO" log.levelDescriptions[.notice] = "NOTICE" log.levelDescriptions[.warning] = "WARN" log.levelDescriptions[.error] = "ERROR" log.levelDescriptions[.severe] = "CRITICAL" log.levelDescriptions[.alert] = "ALERT" log.levelDescriptions[.emergency] = "EMERGENCY" log.info("Server started") // Output: 2024-01-15 10:30:45.123 [INFO] [Server.swift:50] start() > Server started // Emoji level descriptions log.levelDescriptions[.verbose] = "đŸ—¯" log.levelDescriptions[.debug] = "🔹" log.levelDescriptions[.info] = "â„šī¸" log.levelDescriptions[.notice] = "âœŗī¸" log.levelDescriptions[.warning] = "âš ī¸" log.levelDescriptions[.error] = "â€ŧī¸" log.levelDescriptions[.severe] = "đŸ’Ŗ" log.levelDescriptions[.alert] = "🛑" log.levelDescriptions[.emergency] = "🚨" // Per-destination level descriptions if let fileDestination = log.destination(withIdentifier: XCGLogger.Constants.fileDestinationIdentifier) as? FileDestination { fileDestination.levelDescriptions[.error] = "ERR" fileDestination.levelDescriptions[.warning] = "WRN" } ``` -------------------------------- ### Filter Logs by File Name in Swift Source: https://context7.com/davewoodcom/xcglogger/llms.txt Applies filters to include or exclude log messages based on the source file name. Filters can be applied globally or to specific destinations. ```swift import XCGLogger let log = XCGLogger.default // Exclude logs from specific files log.filters = [ FileNameFilter(excludeFrom: ["NoisyClass.swift", "VerboseHelper.swift"], excludePathWhenMatching: true) ] // Or: Include ONLY logs from specific files (inverse filter) log.filters = [ FileNameFilter(includeFrom: ["ImportantController.swift", "CriticalService.swift"]) ] // Filters can be applied to specific destinations if let fileDestination = log.destination(withIdentifier: XCGLogger.Constants.fileDestinationIdentifier) as? FileDestination { // Only log messages from these files to the file destination fileDestination.filters = [ FileNameFilter(includeFrom: ["NetworkManager.swift", "DataService.swift"]) ] } // Set destination filters to empty array to disable all filtering for that destination // while other destinations still use log.filters fileDestination.filters = [] log.debug("This message will be filtered based on which file it's called from") ``` -------------------------------- ### Filter Logs by Tags in Swift Source: https://context7.com/davewoodcom/xcglogger/llms.txt Categorizes log messages using tags and filters output based on those tags. Supports complex tagging using custom structs and bitwise-like operators. ```swift import XCGLogger let log = XCGLogger.default // Define tag key shortcut let tags = XCGLogger.Constants.userInfoKeyTags // Log messages with tags log.debug("Processing user data", userInfo: [tags: "sensitive"]) log.debug("Button tapped", userInfo: [tags: "ui"]) log.debug("API response received", userInfo: [tags: ["network", "api"]]) // Multiple tags // Exclude messages with specific tags log.filters = [ TagFilter(excludeFrom: ["sensitive", "verbose"]) ] // Or: Include ONLY messages with specific tags log.filters = [ TagFilter(includeFrom: ["critical", "error"]) ] // Using Tag helper struct (with UserInfoHelpers) extension Tag { static let sensitive = Tag("sensitive") static let ui = Tag("ui") static let network = Tag("network") } extension Dev { static let alice = Dev("alice") static let bob = Dev("bob") } // Combine tags and developer attribution with | operator log.debug("Network request", userInfo: Dev.alice | Tag.network) log.debug("Sensitive operation", userInfo: Tag.sensitive | Dev.bob) log.debug("UI update", userInfo: Tag.ui.dictionary) // Single tag needs .dictionary ``` -------------------------------- ### Selectively Execute Log Code Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Use closures to prevent expensive string interpolation or calculations when the log level is suppressed. ```Swift log.debug("The description of \(thisObject) is really expensive to create") ``` ```Swift log.debug { var total = 0.0 for receipt in receipts { total += receipt.total } return "Total of all receipts: \(total)" } ``` -------------------------------- ### Tag Log Messages Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Attach user-defined data, such as tags, to log messages using the `userInfo` dictionary. The tag key is accessed via `XCGLogger.Constants.userInfoKeyTags`. The tag value can be a String, Array, or Set. ```Swift let tags = XCGLogger.Constants.userInfoKeyTags log.debug("A tagged log message", userInfo: [tags: "Sensitive"]) ``` -------------------------------- ### Exclude Logs by Filename Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Use `FileNameFilter` to exclude log messages originating from specific files. Set `excludePathWhenMatching` to `true` (default) to match the full path, or `false` to match only the filename. ```Swift log.filters = [FileNameFilter(excludeFrom: ["AppDelegate.swift"], excludePathWhenMatching: true)] ``` -------------------------------- ### Log Messages at Different Levels Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Use convenience methods to log messages at various severity levels. XCGLogger only prints messages with a log level greater than or equal to its current setting. ```Swift log.verbose("A verbose message, usually useful when working on a specific problem") ``` ```Swift log.debug("A debug message") ``` ```Swift log.info("An info message, probably useful to power users looking in console.app") ``` ```Swift log.notice("A notice message") ``` ```Swift log.warning("A warning message, may indicate a possible error") ``` ```Swift log.error("An error occurred, but it's recoverable, just info about what happened") ``` ```Swift log.severe("A severe error occurred, we are likely about to crash now") ``` ```Swift log.alert("An alert error occurred, a log destination could be made to email someone") ``` ```Swift log.emergency("An emergency error occurred, a log destination could be made to text someone") ``` -------------------------------- ### Log Any Data Type Source: https://context7.com/davewoodcom/xcglogger/llms.txt Log various data types including primitives, collections, optionals, and custom types conforming to `CustomStringConvertible`. XCGLogger automatically converts values for logging. ```swift import XCGLogger let log = XCGLogger.default // Log various types log.debug("String message") log.debug(42) log.debug(3.14159) log.debug(true) log.debug(CGPoint(x: 100, y: 200)) log.debug(["key": "value", "count": 42]) log.debug(["apple", "banana", "cherry"]) log.debug((name: "John", age: 30)) // Log custom types (uses CustomStringConvertible if available) struct User: CustomStringConvertible { let id: Int let name: String var description: String { "User(id: \(id), name: \(name))" } } let user = User(id: 1, name: "Alice") log.debug(user) // Output: 2024-01-15 10:30:45.123 [Debug] [UserManager.swift:25] loadUser() > User(id: 1, name: Alice) // Log optionals let optionalValue: String? = nil log.debug(optionalValue as Any) // Outputs: nil // Log errors enum AppError: Error { case networkFailure, invalidData } log.error(AppError.networkFailure) ``` -------------------------------- ### Configure Custom Date Formats for Log Timestamps Source: https://context7.com/davewoodcom/xcglogger/llms.txt Set a custom date format for log timestamps by assigning a configured DateFormatter to the logger's dateFormatter property. This affects all log messages. ```swift import XCGLogger let log = XCGLogger.default // Create custom date formatter let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" dateFormatter.locale = Locale.current dateFormatter.timeZone = TimeZone.current log.dateFormatter = dateFormatter // ISO 8601 format let isoFormatter = DateFormatter() isoFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" log.dateFormatter = isoFormatter // Short format for debugging let shortFormatter = DateFormatter() shortFormatter.dateFormat = "HH:mm:ss.SSS" log.dateFormatter = shortFormatter log.debug("Message with custom timestamp") // Output with short format: 10:30:45.123 [Debug] [MyFile.swift:10] myFunction() > Message with custom timestamp ``` -------------------------------- ### Filter Logs by Tag Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Create a `TagFilter` to include or exclude log messages based on the tags defined in their `userInfo`. Use `excludeFrom:` to specify tags to exclude. ```Swift let sensitiveTag = "Sensitive" log.filters = [TagFilter(excludeFrom: [sensitiveTag])] ``` -------------------------------- ### Filter Logs by Developer Source: https://github.com/davewoodcom/xcglogger/blob/main/README.md Similar to tag filtering, use `UserInfoFilter` with the `XCGLogger.Constants.userInfoKeyDevs` key to filter logs by developer. This is a subclass of `UserInfoFilter`. ```Swift log.filters = [UserInfoFilter(excludeFrom: ["developerName"], key: XCGLogger.Constants.userInfoKeyDevs)] ``` -------------------------------- ### Add ANSI Color Formatting to File Logs Source: https://context7.com/davewoodcom/xcglogger/llms.txt Customize log message colors for different levels using ANSI escape codes. This formatter is applied to a FileDestination. View colored output by viewing the log file in a terminal. ```swift import XCGLogger let log = XCGLogger.default // Get file destination and add color formatter if let fileDestination = log.destination(withIdentifier: XCGLogger.Constants.fileDestinationIdentifier) as? FileDestination { let ansiFormatter = ANSIColorLogFormatter() // Customize colors for each level ansiFormatter.colorize(level: .verbose, with: .colorIndex(number: 244), options: [.faint]) ansiFormatter.colorize(level: .debug, with: .black) ansiFormatter.colorize(level: .info, with: .blue, options: [.underline]) ansiFormatter.colorize(level: .notice, with: .green, options: [.italic]) ansiFormatter.colorize(level: .warning, with: .yellow) ansiFormatter.colorize(level: .error, with: .red, options: [.bold]) ansiFormatter.colorize(level: .severe, with: .white, on: .red) ansiFormatter.colorize(level: .alert, with: .white, on: .red, options: [.bold]) ansiFormatter.colorize(level: .emergency, with: .white, on: .red, options: [.bold, .blink]) // RGB colors ansiFormatter.colorize(level: .info, with: .rgb(red: 100, green: 150, blue: 200)) fileDestination.formatters = [ansiFormatter] } // View colored output: cat /path/to/app.log (in Terminal) // Or: tail -f /path/to/app.log ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.