93

I would like to globally ignore all println() calls in my Swift code if I am not in a Debug build. I can't find any robust step by step instructions for this and would appreciate guidance. is there a way to do this globally, or do I need to surround every println() with #IF DEBUG/#ENDIF statements?

LC 웃
  • 18,888
  • 9
  • 57
  • 72
Nate Birkholz
  • 2,739
  • 4
  • 20
  • 29
  • possible duplicate of [Disabling NSLog For Production In Swift Project](http://stackoverflow.com/questions/26890537/disabling-nslog-for-production-in-swift-project) – David Berry Nov 13 '14 at 20:02
  • 7
    print no longer outputs in Device Console but does in debugger console..Hence no need to remove for release version. – LC 웃 Mar 11 '16 at 11:57
  • 1
    As of Xcode 8 and swift 3 I don't see prints in console in release mode. – CiNN Dec 20 '16 at 10:53

18 Answers18

106

The simplest way is to put your own global function in front of Swift's println:

func println(object: Any) {
    Swift.println(object)
}

When it's time to stop logging, just comment out the body of that function:

func println(object: Any) {
    // Swift.println(object)
}

Or you can make it automatic by using a conditional:

func println(object: Any) {
    #if DEBUG
        Swift.println(object)
    #endif
}

EDIT In Swift 2.0 println is changed to print. Unfortunately it now has a variadic first parameter; this is cool, but it means you can't easily override it because Swift has no "splat" operator so you can't pass a variadic in code (it can only be created literally). But you can make a reduced version that works if, as will usually be the case, you are printing just one value:

func print(items: Any..., separator: String = " ", terminator: String = "\n") {
    Swift.print(items[0], separator:separator, terminator: terminator)
}

In Swift 3, you need to suppress the external label of the first parameter:

func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
    Swift.print(items[0], separator:separator, terminator: terminator)
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 3
    Nice solution, thanks. I have been told that in iOS (but not OS X), ```println()``` isn't executed in release mode. – Nate Birkholz Jan 26 '15 at 20:40
  • 13
    @NateBirkholz No, that's nonsense. (Said he, after testing to make sure!) – matt Jan 26 '15 at 21:26
  • In swift 2, with the function renamed to print, would you just chance the func to match? Also, how would you define this globally? I tried putting it outside my class in AppDelegate and it just isn't ever called even though I have a million print() calls. Here's what I tried: func print(object: Any) { Swift.print(object) } – Charlie Oct 12 '15 at 14:49
  • @Charlie Yes, I'm still using it with `println` changed to `print`. The reason it isn't working for you is that your `print` definition doesn't match Swift's, so you are not overriding it. There is a slight issue because, as has been remarked many times, Swift has no splat operator, so you can't pass the variadic. But it works fine for one item, which you can pass as `items[0]`. – matt Oct 12 '15 at 15:16
  • 3
    One caveat here if you are inserting these log statements into high performance sections of code: Swift will still spend time doing string interpolation and rendering parameters to pass to the function, even if they aren't going to be used. The only way that I see to really conditionally remove the statements is to predicate them on a flag. e.g. if ( log ) { print(..) } in each location where they are used. – Pat Niemeyer Nov 07 '15 at 19:38
  • This should be the acccepted answer. or we could simply use Swift.debugPrint() instead to turn off all the prints in release mode. – Abdul Yasin Apr 04 '16 at 10:11
  • @PatNiemeyer Okay, I've solved that by using `@autoclosure`. That's far enough from my original answer that I've given it as a separate answer. – matt Jul 12 '16 at 17:47
  • Is it necessary to remove all "print()" before releasing app on AppStore ? – Nitesh Nov 07 '16 at 07:24
  • What about iOS SDK? Will the i#f DEBUG work there as well ? – nr5 Sep 07 '20 at 06:15
  • Why are you accepting `Any...` for `items` but only using the first one? Shouldn't you just accept `Any`? Or is your code just meant as an example of how you could pass through some number of items? – deaton.dg Jun 01 '21 at 17:13
  • 1
    The caveat to this is `items[0]` will only print the first item in the series of items passed into the custom print function. You could pass `items` to `Swift.print` instead to print all of them. However, the line will be surrounded in array brackets. E.g. `print("Hello", "there")` would output `[Hello there]` – Drew Jul 11 '21 at 04:11
48

Updated for Swift 4.x:

With Swift 2.0/3.0 and Xcode 7/8 now out of beta, there have been some changes to how you disable the print function in release builds.

There are some important points mentioned by @matt and @Nate Birkholz above that are still valid.

  1. The println() function has been replaced by print()

  2. To use the #if DEBUG macro then you have to define the "Swift Compiler - Custom Flags -Other Flags" to contain the value -D DEBUG

  3. I would recommend overriding the Swift.print() function in the global scope so that you can use the print() function as normal in your code, but it will remove output for non-debug builds. Here is a function signature that you can add at the global scope to do this in Swift 2.0/3.0:

    func print(items: Any..., separator: String = " ", terminator: String = "\n") {
    
        #if DEBUG
    
        var idx = items.startIndex
        let endIdx = items.endIndex
    
        repeat {
            Swift.print(items[idx], separator: separator, terminator: idx == (endIdx - 1) ? terminator : separator)
            idx += 1
        }
        while idx < endIdx
    
        #endif
    }
    

Note: We have set the default separator to be a space here, and the default terminator to be a newline. You can configure this differently in your project if you would like.

Hope this helps.

Update:

It is usually preferable to put this function at the global scope, so that it sits in front of Swift's print function. I find that the best way to organize this is to add a utility file to your project (like DebugOptions.Swift) where you can place this function at the global scope.

As of Swift 3 the ++ operator will be deprecated. I have updated the snippet above to reflect this change.

Glavid
  • 1,071
  • 9
  • 19
  • 1
    I am sorry, but where to put the function? – DàChún Oct 28 '15 at 15:57
  • @User9527 Likely you want to put this somewhere in the global scope, so that it is accessible throughout your project. In my projects, I add a utility swift file (DebugOptions.swift or something similar) and place this function in the global scope (i.e. not in an enclosed class). – Glavid Nov 03 '15 at 00:53
  • Can you confirm as of current version of Swift-Xcode, the print statement will no longer output to device console without any need to set the -D Debug flat? At least that is what I have tested today. – user523234 Apr 10 '16 at 19:40
  • @user523234 As of Xcode 7.3, if you want the Debug output to print when *in Debug mode, you still need to set the debug flag per my testing.. – Glavid Apr 11 '16 at 18:31
  • 1
    As of Swift 3, one can get a little more brevity by adding an underscore at the start of the list of arguments: "print (_ items..." – Jonathan Zhan Jul 22 '16 at 10:46
  • I'm new to Swift (3), and I put the `print` above into its own swift file, but it does nothing. – Jonny Mar 22 '17 at 01:54
  • 8
    So I looked up the reference of the print (used in didFinishLaunching...) and it pointed me to the original print function Swift. Putting that and @JonathanZhan's comment together, I adjusted the function to look like this and voila it works: `public func print(_ items: Any..., separator: String = " ", terminator: String = "\n") { ` – Jonny Mar 22 '17 at 01:56
  • Add it anywhere in the project but outside of a class and beware of the parameters to override print function as above it little different try func print(_ items: Any..., separator: String = " ", terminator: String = "\n") Add underscore in items parameter. – Darshan Mothreja Apr 07 '20 at 11:30
  • not working, compile error `Invalid redeclaration of 'print(_:separator:terminator:)'` – Yiming Dong Apr 16 '23 at 03:58
44

The problem with all these approaches, including mine, is that they do not remove the overhead of evaluating the print arguments. No matter which of them you use, this is going to be expensive:

print(myExpensiveFunction())

The only decent solution is to wrap the actual print call in conditional compilation (let's assume that DEBUG is defined only for debug builds):

#if DEBUG
print(myExpensiveFunction())
#endif

That, and only that, prevents myExpensiveFunction from being called in a release build.

However, you can push back evaluation one level by using autoclosure. Thus, you could rewrite my solution (this is Swift 3) like this:

func print(_ item: @autoclosure () -> Any, separator: String = " ", terminator: String = "\n") {
    #if DEBUG
    Swift.print(item(), separator: separator, terminator: terminator)
    #endif
}

This solves the problem just in the case where you are printing just one thing, which is usually true. That's because item() is not called in release mode. print(myExpensiveFunction()) thus ceases to be expensive, because the call is wrapped in a closure without being evaluated, and in release mode, it won't be evaluated at all.

Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • What the use of `@autoclosure`? – kelin Mar 05 '17 at 08:53
  • @matt in your book, you mention "An important feature of print is that it is effectively suppressed when the app is launched independently of Xcode", does that mean we can leave our print statements in our submitted apps these days, or am I misunderstanding something? – hidden-username Nov 21 '18 at 19:20
  • @hidden-username Yes, I tend to leave my `print` statements in my shipping code, but that's different from what my answer here is about. A `print` statement output is not sent to the console in your Xcode-independent release build, but it is still _evaluated_, so it remains useful to know how to suppress that evaluation just in case it is expensive or has unwanted side effects. – matt Nov 21 '18 at 21:51
  • @matt oh ok...Yeah I misunderstood it. I'll comment them out. Thanks – hidden-username Nov 21 '18 at 23:03
  • 1
    Will this approach remove the printed string from binary file? For example if I used that method and somewhere in my app I put "print("user logged in")" and then if someone tries to reverse engineer my app will he find this string somewhere or it won't be there at all? – Leszek Szary Dec 23 '19 at 07:41
  • 3
    I suggest to also add `@available(*, unavailable, message: "Use single argument print(item: Any) instead") func print(_ items: Any..., separator: String = " ", terminator: String = "\n") { }` to avoid using the multi argument print by mistake – Kazikal Jan 17 '22 at 11:39
  • @Kazikal nice idea! – matt Jan 17 '22 at 11:44
27

Easy Answer - Xcode 14, Swift 5

Create a new file in your project and paste in this code:

import Foundation

func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
    #if DEBUG
    Swift.print(items, separator: separator, terminator: terminator)
    #endif
}

This function signature matches the default Swift print so it overwrites the function throughout your project. If needed you can still access the original by using Swift.print().

Once you've added the code above, keep using print() the as usual and it will only print in debug builds.

Trev14
  • 3,626
  • 2
  • 31
  • 40
  • 2
    where to declare this function, is this is some extension or smth like this? I just don't want to declare it in each file) – Matrosov Oleksandr Aug 13 '19 at 09:05
  • 1
    @MatrosovAlexander You can just create a swift file anywhere in your app project and put this code in. The compiler is smart enough to make it globally accessible. – Trev14 Aug 13 '19 at 17:04
22

As noted, i am a student and need things defined a little more clearly to follow along. After lots of research, the sequence I needed to follow is:

Click on the project name at the top of the File Navigator at the left of the Xcode project window. This is line that has the name of the project, how many build targets there are, and the iOS SDK version.

Choose the Build Settings tab and scroll down to the "Swift Compiler - Custom Flags" section near the bottom. Click the Down Arrow next to Other Flags to expand the section.

Click on the Debug line to select it. Place your mouse cursor over the right side of the line and double-click. A list view will appear. Click the + button at the lower left of the list view to add a value. A text field will become active.

In the text field, enter the text -D DEBUG and press Return to commit the line.

Add a new Swift file to your project. You are going to want to make a custom class for the file, so enter text along the lines of the following:

class Log {

  var intFor : Int

  init() {
    intFor = 42
   }

  func DLog(message: String, function: String = __FUNCTION__) {
    #if DEBUG
      println("\(function): \(message)")
    #endif
  }
}

I was having trouble getting the class to be accepted by Xcode today, so the init may be a bit more heavyweight than necessary.

Now you will need to reference your custom class in any class in which you intend to use the new custom function in place of println() Add this as a property in every applicable class:

   let logFor = Log()

Now you can replace any instances of println() with logFor.DLog(). The output also includes the name of the function in which the line was called.

Note that inside class functions I couldn't call the function unless I made a copy of the function as a class function in that class, and println() is also a bit more flexible with the input, so I couldn't use this in every instance in my code.

Nate Birkholz
  • 2,739
  • 4
  • 20
  • 29
12

Here is a function that I use, which works perfectly in Swift 3:

func gLog<T>( _ object: @autoclosure() -> T, _ file: String = #file, _ function: String = #function, _ line: Int = #line)
    {
    #if DEBUG
        let value = object()
        let stringRepresentation: String

        if let value = value as? CustomDebugStringConvertible
            {
            stringRepresentation = value.debugDescription
            }
        else if let value = value as? CustomStringConvertible
            {
            stringRepresentation = value.description
            }
        else
            {
            fatalError("gLog only works for values that conform to CustomDebugStringConvertible or CustomStringConvertible")
            }

        let fileURL = NSURL(string: file)?.lastPathComponent ?? "Unknown file"
        let queue = Thread.isMainThread ? "UI" : "BG"
    let gFormatter = DateFormatter()
    gFormatter.dateFormat = "HH:mm:ss:SSS"
        let timestamp = gFormatter.string(from: Date())

        print("✅ \(timestamp) {\(queue)} \(fileURL) > \(function)[\(line)]: " + stringRepresentation + "\n")
    #endif
    }

Here is an example of the output it generates:

screenshot of output

Explanation:

  • the green checkmark is used to enable you to quickly see your print (gLog) messages in the console, where they can sometimes get lost in a sea of other messages

  • the time/date stamp

  • the thread it is being run on -- in my case it is either the MainThread (which I call UI), or not the MainThread (which I call BG, for background thread)

  • the name of the file that the gLog message resides in

  • the function within the file that the gLog message resides in

  • the line number of the gLog message

  • the actual gLog message you would like to print out

Hope this is useful to someone else!

Gene Loparco
  • 2,157
  • 23
  • 23
  • can this be put into a separate file to be used all across the app ? I tried putting it in a separate class file, as a class method. But it crashes with libMobileGestalt MobileGestaltSupport.m:153: pid 2574 (Demo) does not have sandbox access for frZQaeyWLUvLjeuEK43hmg and IS NOT appropriately entitled libMobileGestalt MobileGestalt.c:550: no access to InverseDeviceID (see ) Message from debugger: Terminated due to memory issue – omarojo Aug 09 '17 at 23:40
  • omarojo, I use this as a global function throughout my app. No class is necessary. I have a file named utils.swift, that contain all of my utility functions, such as this. You just need to make sure to import Foundation - perhaps that is the step you have missed? By the way, for more info on declaring your functions within classes, as static functions within classes, or as global functions, see this SO question and answers: https://stackoverflow.com/questions/30197548/benefits-of-using-class-func-vs-func-vs-no-class-declaration – Gene Loparco Aug 18 '17 at 23:21
  • Yeah, got it working by just creating a new file with the function inside. For some reason having it as a Class Function would crash the app with no clear debug message. – omarojo Aug 19 '17 at 00:14
  • Thanks for this man, shame I did not discovered it before. Saved me a lot of debugging headache. – beowulf Jun 27 '18 at 17:36
  • My pleasure @beowulf! – Gene Loparco Oct 01 '18 at 18:15
9

Tested with Swift 2.1 & Xcode 7.1.1

There's an easy way to exclude all print statements from release versions, once you know that empty functions are removed by the Swift compiler.

Side note : In the era of Objective-C, there was a pre-parser which could be used to remove NSLog statements before the compiler kicked in, like described in my answer here. But since Swift no longer has a pre-parser this approach is no longer valid.

Here's what I use today as an advanced and easily configurable log function, without ever having to worry about removing it in release builds. Also by setting different compiler flags, you can tweak the information that is logged as needed.

You can tweak the function as needed, any suggestion to improve it is welcome!

// Gobal log() function
//
// note that empty functions are removed by the Swift compiler -> use #if $endif to enclose all the code inside the log()
// these log() statements therefore do not need to be removed in the release build !
//
// to enable logging
//
// Project -> Build Settings -> Swift Compiler - Custom flags -> Other Swift flags -> Debug
// add one of these 3 possible combinations :
//
//      -D kLOG_ENABLE
//      -D kLOG_ENABLE -D kLOG_DETAILS
//      -D kLOG_ENABLE -D kLOG_DETAILS -D kLOG_THREADS
//
// you can just call log() anywhere in the code, or add a message like log("hello")
//
func log(message: String = "", filePath: String = #file, line: Int = #line, function: String = #function) {
            #if kLOG_ENABLE

            #if kLOG_DETAILS

            var threadName = ""
            #if kLOG_THREADS
                threadName = NSThread.currentThread().isMainThread ? "MAIN THREAD" : (NSThread.currentThread().name ?? "UNKNOWN THREAD")
                threadName = "[" + threadName + "] "
            #endif

            let fileName = NSURL(fileURLWithPath: filePath).URLByDeletingPathExtension?.lastPathComponent ?? "???"

            var msg = ""
            if message != "" {
                msg = " - \(message)"
            }

            NSLog("-- " + threadName + fileName + "(\(line))" + " -> " + function + msg)
        #else
            NSLog(message)
        #endif
    #endif
}

Here's where you set the compiler flags :

enter image description here

An example output with all flags on looks like this :

   2016-01-13 23:48:38.026 FoodTracker[48735:4147607] -- [MAIN THREAD] ViewController(19) -> viewDidLoad() - hello

The code with the log() looks like this :

    override func viewDidLoad() { log("hello")
    super.viewDidLoad()

   // Handle the text field's user input through delegate callbacks
   nameTextField.delegate = self
}
Community
  • 1
  • 1
Ronny Webers
  • 5,244
  • 4
  • 28
  • 24
  • Nice one! I took it from here and made [AELog](https://github.com/tadija/AELog) and [AEConsole](https://github.com/tadija/AEConsole) eventually. – tadija Apr 04 '16 at 23:11
  • This is working fine in DEBUG mode. Now, I've changed to RELEASE mode from Edit Scheme. It shows the log in console window for Release mode too. Why so? – Jayprakash Dubey Jan 03 '17 at 13:11
  • For Swift 3.2 in Xcode 9 I needed to change NSLog to print and call using log(message:"hello"), also I had to put the flags in as "-D" "kLOG_ENABLE", with the quotes. All other swift version updates were picked up by the compiler with suggested fixes. – iCyberPaul Jul 06 '17 at 11:12
  • 1
    Here you state "empty functions are removed by the Swift compiler", where in the docs do we find that? How do you know that is the case? @ronny-webers – zumzum Jan 02 '18 at 21:29
7

Even simpler, after making sure -D DEBUG is set for the OTHER_SWIFT_FLAGS Debug build settings:

#if !DEBUG
    func print(_ items: Any..., separator: String = " ", terminator: String = "\n") { }
#endif
Axel Guilmin
  • 11,454
  • 9
  • 54
  • 64
Rivera
  • 10,792
  • 3
  • 58
  • 102
  • I suspect this may require a "where" since printable objects conform to one of those system protocols you see mentioned rarely in vids for wwdc, and I think at the end of the swift guide(s) 1.2 vs 2, forgot the difference if there is one with the system one – Stephen J Aug 19 '15 at 00:39
  • So far it this works with Swift 1.2. Haven't tried 2.0. – Rivera Aug 19 '15 at 15:10
6

XCode 8 introduced a few new build settings.
In particular one referred to Active Compilation Conditions does in a similar way what Other Flags settings did.

"Active Compilation Conditions" is a new build setting for passing conditional compilation flags to the Swift compiler.

As per XCode 8 (tested in 8.3.2) you will get this by default:

enter image description here

So without any config you can write the following:

#if DEBUG
    print("⚠️ Something weird happened")
#endif

I strongly recommend you that if you use this approach extensively create a class/struct/function that wraps this logging logic. You may want to extend this further down the road.

Javier Cadiz
  • 12,326
  • 11
  • 55
  • 76
5

Varun Naharia has the better solution so far. I would combine his answer with Rivera's ...

  1. create a -D DEBUG flag on the compiler directives, build settings.
  2. then add this code:

    #if !DEBUG
     public func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
    }
    #endif
    

This code will convert every print into nothing for release.

Duck
  • 34,902
  • 47
  • 248
  • 470
3

Swift 4 Xcode 10.0

maybe you could use this

func dPrint(_ message: @autoclosure () -> Any) {
    #if DEBUG
    print(message())
    #endif
}

The reason of using @autoclosure is that if you pass a function as the message parameter, the function will be called only in debug mode, it will cause a performance hit.

unlike the Swift.print(_ items: Any..., separator: String = default, terminator: String = default) function, my solution has only one parameter, because in most cases, we don't pass multiple parameters as the print function only shows information in console, we can just convert the parameters to String: "\(param1)"+"\(param2)", right? hope u like my solution

1

for my solution i make it simple

import UIKit

class DLog: NSObject {

   init(title:String, log:Any) {
       #if DEBUG
           print(title, log)
       #endif

   }

}

then to show it just call

_ = DLog(title:"any title", log:Any)
1

You can also use a breakpoint, set it to continue after evaluation, and write the print message in the breakpoint!

enter image description here

7RedBits.com
  • 454
  • 6
  • 6
0

You could define debug_println whose contents would be roughly:

#if DEBUG
  println()
#endif
Ian MacDonald
  • 13,472
  • 2
  • 30
  • 51
0

My Solution is use this code in AppDelegate before class

// Disable console log in live app
#if !arch(x86_64) && !arch(i386)
    public func debugPrint(items: Any..., separator: String = " ", terminator: String = "\n") {

    }
    public func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {

    }
#endif

class AppDelegate: UIResponder, UIApplicationDelegate {
// App Delegate Code 

}
Varun Naharia
  • 5,318
  • 10
  • 50
  • 84
0

Even simpler: take advantage of the fact that asserts are removed from release builds and only from there call the print. This removes all log calls (yes, even the calls to Log.da) as they are empty when building for release.

But I also heard that prints are removed for release builds, but not been able to find it in writing. So for now, I am using something like this Log below. I have a more meaty version on GitHub with emojis (for readability) and log topics (for consistency):

https://github.com/Gatada/JBits/blob/master/Project/Utility/Log.swift

public enum Log {

    /// A date formatter used to create the timestamp in the log.
    ///
    /// This formatter is only created if it is actually used, reducing the
    /// overhead to zero.
    static var formatter: DateFormatter?

    // MARK: - API

    /// Call to print message in debug area.
    ///
    /// Asserts are removed in release builds, which make
    /// the function body empty, which caused all calls to
    /// be removed as well.
    ///
    /// Result is zero overhead for release builds.
    public static func da(_ message: String) {
        assert(debugAreaPrint(message))
    }

    // MARK: - Helpers

    /// The function that actually does the printing. It returns `true` to
    /// prevent the assert from kicking in on debug builds.
    private static func debugAreaPrint(_ message: String) -> Bool {
        print("\(timestamp) - \(message)")
        return true
    }

    /// Creates a timestamp used as part of the temporary logging in the debug area.
    static private var timestamp: String {

        if formatter == nil {
            formatter = DateFormatter()
            formatter!.dateFormat = "HH:mm:ss.SSS"
        }

        let date = Date()
        return formatter!.string(from: date)
    }
}

In code:

Log.da("This is only handled in a debug build.")

Seen in the Xcode debug area only when running a debug build:

13:36:15.047 - This is only handled in a debug build.

Johan
  • 2,472
  • 1
  • 23
  • 25
0

My Project was developed in Objective C, but from the past year I have started merging new code in Swift, So In Swift below solution worked for me, I have added that code in My Swift constant file :

func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
    #if DEBUG
    items.forEach {
        Swift.print($0, separator: separator, terminator: terminator)
    }
    #endif
}
David Buck
  • 3,752
  • 35
  • 31
  • 35
PoojaArora
  • 31
  • 3
0

This works for me (add this as a global function in the project)

func print(_ items: Any...) {
    #if DEBUG
        Swift.print(items[0])
    #endif
}
harryngh
  • 1,789
  • 1
  • 13
  • 6