Need help with XCGLogger?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

3.7K Stars 450 Forks MIT License 413 Commits 42 Opened issues


A debug log framework for use in Swift projects. Allows you to log details to the console (and optionally a file), just like you would have with NSLog() or print(), but with additional information, such as the date, function name, filename and line number.

Services available


Need anything else?

Contributors list


badge-language badge-platforms badge-license

badge-travis badge-swiftpm badge-cocoapods badge-carthage

badge-mastodon badge-twitter

badge-sponsors badge-patreon


XCGLogger is the original debug log module for use in Swift projects.

Swift does not include a C preprocessor so developers are unable to use the debug log

macros they would use in Objective-C. This means our traditional way of generating nice debug logs no longer works. Resorting to just plain old
calls means you lose a lot of helpful information, or requires you to type a lot more code.

XCGLogger allows you to log details to the console (and optionally a file, or other custom destinations), just like you would have with

, but with additional information, such as the date, function name, filename and line number.

Go from this:

Simple message

to this:

2014-06-09 06:44:43.600 [Debug] [AppDelegate.swift:40] application(_:didFinishLaunchingWithOptions:): Simple message



Communication (Hat Tip AlamoFire)

  • If you need help, use Stack Overflow (Tag 'xcglogger').
  • If you'd like to ask a general question, use Stack Overflow.
  • If you've found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.
  • If you use XCGLogger, please Star the project on GitHub


Git Submodule


git submodule add

in your repository folder.


Add the following line to your


github "DaveWoodCom/XCGLogger" ~> 7.0.1

Then run

carthage update --no-use-binaries
or just
carthage update
. For details of the installation and usage of Carthage, visit its project page.

Developers running 5.0 and above in Swift will need to add

to their Input Files in the Copy Carthage Frameworks Build Phase.


Add something similar to the following lines to your

. You may need to adjust based on your platform, version/branch etc.
source ''
platform :ios, '8.0'

pod 'XCGLogger', '~> 7.0.1'

Specifying the pod

on its own will include the core framework. We're starting to add subspecs to allow you to include optional components as well:

pod 'XCGLogger/UserInfoHelpers', '~> 7.0.1'
: Include some experimental code to help deal with using UserInfo dictionaries to tag log messages.

Then run

pod install
. For details of the installation and usage of CocoaPods, visit its official web site.

Note: Before CocoaPods 1.4.0 it was not possible to use multiple pods with a mixture of Swift versions. You may need to ensure each pod is configured for the correct Swift version (check the targets in the pod project of your workspace). If you manually adjust the Swift version for a project, it'll reset the next time you run

pod install
. You can add a
hook into your podfile to automate setting the correct Swift versions. This is largely untested, and I'm not sure it's a good solution, but it seems to work:
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'
            print "Setting #{target}'s SWIFT_VERSION to Undefined (Xcode will automatically resolve)\n"
            target.build_configurations.each do |config|

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'


You can adjust that to suit your needs of course.

Swift Package Manager

Add the following entry to your package's dependencies:

.Package(url: "", majorVersion: 7)

Backwards Compatibility

Use: * XCGLogger version 7.0.1 for Swift 5.0 * XCGLogger version 6.1.0 for Swift 4.2 * XCGLogger version 6.0.4 for Swift 4.1 * XCGLogger version 6.0.2 for Swift 4.0 * XCGLogger version 5.0.5 for Swift 3.0-3.2 * XCGLogger version 3.6.0 for Swift 2.3 * XCGLogger version 3.5.3 for Swift 2.2 * XCGLogger version 3.2 for Swift 2.0-2.1 * XCGLogger version 2.x for Swift 1.2 * XCGLogger version 1.x for Swift 1.1 and below.

Basic Usage (Quick Start)

This quick start method is intended just to get you up and running with the logger. You should however use the advanced usage below to get the most out of this library.

Add the XCGLogger project as a subproject to your project, and add the appropriate library as a dependency of your target(s). Under the

tab of your target, add
to the
Embedded Binaries

Then, in each source file:

import XCGLogger

In your AppDelegate (or other global file), declare a global constant to the default XCGLogger instance.

let log = XCGLogger.default

In the

application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil) // iOS, tvOS


applicationDidFinishLaunching(_ notification: Notification) // macOS

function, configure the options you need:

log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: "path/to/file", fileLevel: .debug)

The value for

can be a
. If the file already exists, it will be cleared before we use it. Omit the parameter or set it to
to log to the console only. You can optionally set a different log level for the file output using the
parameter. Set it to
or omit it to use the same log level as the console.

Then, whenever you'd like to log something, use one of the convenience methods:

log.verbose("A verbose message, usually useful when working on a specific problem")
log.debug("A debug message")"An info message, probably useful to power users looking in")
log.notice("A notice message")
log.warning("A warning message, may indicate a possible error")
log.error("An error occurred, but it's recoverable, just info about what happened")
log.severe("A severe error occurred, we are likely about to crash now")
log.alert("An alert error occurred, a log destination could be made to email someone")
log.emergency("An emergency error occurred, a log destination could be made to text someone")

The different methods set the log level of the message. XCGLogger will only print messages with a log level that is greater to or equal to its current log level setting. So a logger with a level of

will only output log messages with a level of
, or

Advanced Usage (Recommended)

XCGLogger aims to be simple to use and get you up and running quickly with as few as 2 lines of code above. But it allows for much greater control and flexibility.

A logger can be configured to deliver log messages to a variety of destinations. Using the basic setup above, the logger will output log messages to the standard Xcode debug console, and optionally a file if a path is provided. It's quite likely you'll want to send logs to more interesting places, such as the Apple System Console, a database, third party server, or another application such as NSLogger. This is accomplished by adding the destination to the logger.

Here's an example of configuring the logger to output to the Apple System Log as well as a file.

// 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")

// Optionally set some configuration options systemDestination.outputLevel = .debug systemDestination.showLogIdentifier = false systemDestination.showFunctionName = true systemDestination.showThreadName = true systemDestination.showLevel = true systemDestination.showFileName = true systemDestination.showLineNumber = true systemDestination.showDate = 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")

// Optionally set some configuration options fileDestination.outputLevel = .debug fileDestination.showLogIdentifier = false fileDestination.showFunctionName = true fileDestination.showThreadName = true fileDestination.showLevel = true fileDestination.showFileName = true fileDestination.showLineNumber = true fileDestination.showDate = true

// Process this destination in the background fileDestination.logQueue = XCGLogger.logQueue

// Add the destination to the logger log.add(destination: fileDestination)

// Add basic app info, version info etc, to the start of the logs log.logAppDetails()

You can configure each log destination with different options depending on your needs.

Another common usage pattern is to have multiple loggers, perhaps one for UI issues, one for networking, and another for data issues.

Each log destination can have its own log level. As a convenience, you can set the log level on the log object itself and it will pass that level to each destination. Then set the destinations that need to be different.

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

Initialization Using A Closure

Alternatively you can use a closure to initialize your global variable, so that all initialization is done in one place ```Swift let log: XCGLogger = { let log = XCGLogger(identifier: "advancedLogger", includeDefaultDestinations: false)

// Customize as needed

return log

}() ```

Note: This creates the log object lazily, which means it's not created until it's actually needed. This delays the initial output of the app information details. Because of this, I recommend forcing the log object to be created at app launch by adding the line

let _ = log
at the top of your
method if you don't already log something on app launch.

Log Anything

You can log strings:

log.debug("Hi there!")

or pretty much anything you want:

log.debug(CGPoint(x: 1.1, y: 2.2))
log.debug((4, 2))
log.debug(["Device": "iPhone", "Version": 7])

Filtering Log Messages

New to XCGLogger 4, you can now create filters to apply to your logger (or to specific destinations). Create and configure your filters (examples below), and then add them to the logger or destination objects by setting the optional

property to an array containing the filters. Filters are applied in the order they exist in the array. During processing, each filter is asked if the log message should be excluded from the log. If any filter excludes the log message, it's excluded. Filters have no way to reverse the exclusion of another filter.

If a destination's

property is
, the log's
property is used instead. To have one destination log everything, while having all other destinations filter something, add the filters to the log object and set the one destination's
property to an empty array

Note: Unlike destinations, you can add the same filter object to multiple loggers and/or multiple destinations.

Filter by Filename

To exclude all log messages from a specific file, create an exclusion filter like so:

log.filters = [FileNameFilter(excludeFrom: ["AppDelegate.swift"], excludePathWhenMatching: true)]

takes an
so you can specify multiple files at the same time.

defaults to
so you can omit it unless you want to match path's as well.

To include log messages only for a specific set to files, create the filter using the

initializer. It's also possible to just toggle the
property to flip the exclusion filter to an inclusion filter.

Filter by Tag

In order to filter log messages by tag, you must of course be able to set a tag on the log messages. Each log message can now have additional, user defined data attached to them, to be used by filters (and/or formatters etc). This is handled with a

userInfo: Dictionary
object. The dictionary key should be a namespaced string to avoid collisions with future additions. Official keys will begin with
. The tag key can be accessed by
. You definitely don't want to be typing that, so feel free to create a global shortcut:
let tags = XCGLogger.Constants.userInfoKeyTags
. Now you can easily tag your logs:
let sensitiveTag = "Sensitive"
log.debug("A tagged log message", userInfo: [tags: sensitiveTag])

The value for tags can be an

, or just a
, depending on your needs. They'll all work the same way when filtered.

Depending on your workflow and usage, you'll probably create faster methods to set up the

dictionary. See below for other possible shortcuts.

Now that you have your logs tagged, you can filter easily:

log.filters = [TagFilter(excludeFrom: [sensitiveTag])]

Just like the

, you can use
or toggle
to include only log messages that have the specified tags.

Filter by Developer

Filtering by developer is exactly like filtering by tag, only using the

key of
. In fact, both filters are subclasses of the
class that you can use to create additional filters. See Extending XCGLogger below.

Mixing and Matching

In large projects with multiple developers, you'll probably want to start tagging log messages, as well as indicate the developer that added the message.

While extremely flexible, the

dictionary can be a little cumbersome to use. There are a few possible methods you can use to simply things. I'm still testing these out myself so they're not officially part of the library yet (I'd love feedback or other suggestions).

I have created some experimental code to help create the UserInfo dictionaries. (Include the optional

subspec if using CocoaPods). Check the iOS Demo app to see it in use.

There are two structs that conform to the


You can create an extension on each of these that suit your project. For example:

extension Tag {
    static let sensitive = Tag("sensitive")
    static let ui = Tag("ui")
    static let data = Tag("data")

extension Dev { static let dave = Dev("dave") static let sabby = Dev("sabby") }

Along with these types, there's an overloaded operator

that can be used to merge them together into a dictionary compatible with the
parameter of the logging calls.

Then you can log messages like this:

log.debug("A tagged log message", userInfo: Dev.dave | Tag.sensitive)

There are some current issues I see with these

, which is why I've made it optional/experimental for now. I'd love to hear comments/suggestions for improvements.
  1. The overloaded operator
    merges dictionaries so long as there are no
    s. If one of the dictionaries contains a
    , it'll use one of them, without merging them. Preferring the left hand side if both sides have a set for the same key.
  2. Since the
    parameter needs a dictionary, you can't pass in a single Dev or Tag object. You need to use at least two with the
    operator to have it automatically convert to a compatible dictionary. If you only want one Tag for example, you must access the
    parameter manually:
    userInfo: Tag("Blah").dictionary

Selectively Executing Code

All log methods operate on closures. Using the same syntactic sugar as Swift's

function, this approach ensures we don't waste resources building log messages that won't be output anyway, while at the same time preserving a clean call site.

For example, the following log statement won't waste resources if the debug log level is suppressed:

log.debug("The description of \(thisObject) is really expensive to create")

Similarly, let's say you have to iterate through a loop in order to do some calculation before logging the result. In Objective-C, you could put that code block between

, and prevent the code from running. But in Swift, previously you would need to still process that loop, wasting resources. With
it's as simple as:
log.debug {
    var total = 0.0
    for receipt in receipts {
        total +=

return "Total of all receipts: \(total)"


In cases where you wish to selectively execute code without generating a log line, return

, or use one of the methods:
, and

Custom Date Formats

You can create your own

object and assign it to the logger.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy hh:mma"
dateFormatter.locale = Locale.current
log.dateFormatter = dateFormatter

Enhancing Log Messages With Colour

XCGLogger supports adding formatting codes to your log messages to enable colour in various places. The original option was to use the XcodeColors plug-in. However, Xcode (as of version 8) no longer officially supports plug-ins. You can still view your logs in colour, just not in Xcode at the moment. You can use the ANSI colour support to add colour to your fileDestination objects and view your logs via a terminal window. This gives you some extra options such as adding Bold, Italics, or (please don't) Blinking!

Once enabled, each log level can have its own colour. These colours can be customized as desired. If using multiple loggers, you could alternatively set each logger to its own colour.

An example of setting up the ANSI formatter:

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]

As with filters, you can use the same formatter objects for multiple loggers and/or multiple destinations. If a destination's

property is
, the logger's
property will be used instead.

See Extending XCGLogger below for info on creating your own custom formatters.

Alternate Configurations

By using Swift build flags, different log levels can be used in debugging versus staging/production. Go to Build Settings -> Swift Compiler - Custom Flags -> Other Swift Flags and add

to the Debug entry.
    log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true)
    log.setup(level: .severe, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true)

You can set any number of options up in a similar fashion. See the updated iOSDemo app for an example of using different log destinations based on options, search for


Background Log Processing

By default, the supplied log destinations will process the logs on the thread they're called on. This is to ensure the log message is displayed immediately when debugging an application. You can add a breakpoint immediately after a log call and see the results when the breakpoint hits.

However, if you're not actively debugging the application, processing the logs on the current thread can introduce a performance hit. You can now specify a destination process its logs on a dispatch queue of your choice (or even use a default supplied one).

fileDestination.logQueue = XCGLogger.logQueue

or even

fileDestination.logQueue = .background)

This works extremely well when combined with the Alternate Configurations method above.

    log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true)
    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

Append To Existing Log File

When using the advanced configuration of the logger (see Advanced Usage above), you can now specify that the logger append to an existing log file, instead of automatically overwriting it.

Add the optional

parameter when initializing the
object. You can also add the
parameter to add a marker to the log file indicating where a new instance of your app started appending. By default we'll add
-- ** ** ** --
if the parameter is omitted. Set it to
to skip appending the marker.

let fileDestination = FileDestination(writeToFile: "/path/to/file", identifier: "advancedLogger.fileDestination", shouldAppend: true, appendMarker: "-- Relauched App --")

Automatic Log File Rotation

When logging to a file, you have the option to automatically rotate the log file to an archived destination, and have the logger automatically create a new log file in place of the old one.

Create a destination using the

class and set the following properties:

: Auto rotate once the file is larger than this

: Auto rotate after this many seconds

: Number of archived log files to keep, older ones are automatically deleted

Those are all guidelines for the logger, not hard limits.

Extending XCGLogger

You can create alternate log destinations (besides the built in ones). Your custom log destination must implement the

protocol. Instantiate your object, configure it, and then add it to the
object with
. There are two base destination classes (
) you can inherit from to handle most of the process for you, requiring you to only implement one additional method in your custom class. Take a look at
for examples.

You can also create custom filters or formatters. Take a look at the provided versions as a starting point. Note that filters and formatters have the ability to alter the log messages as they're processed. This means you can create a filter that strips passwords, highlights specific words, encrypts messages, etc.


XCGLogger is the best logger available for Swift because of the contributions from the community like you. There are many ways you can help continue to make it great.

  1. Star the project on GitHub.
  2. Report issues/bugs you find.
  3. Suggest features.
  4. Submit pull requests.
  5. Download and install one of my apps: Try my newest app: All the Rings.
  6. You can visit my Patreon and contribute financially.

Note: when submitting a pull request, please use lots of small commits verses one huge commit. It makes it much easier to merge in when there are several pull requests that need to be combined for a new version.

To Do

  • Add more examples of some advanced use cases
  • Add additional log destination types
  • Add Objective-C support
  • Add Linux support


If you find this library helpful, you'll definitely find this other tool helpful:


Also, please check out some of my other projects:

  • All the Rings: App Store
  • Rudoku: App Store
  • TV Tune Up:

Change Log

The change log is now in its own file:

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.