Skip to content

Instantly share code, notes, and snippets.

@xmzio
Last active October 21, 2019 07:31
Show Gist options
  • Save xmzio/fccd29fc945de7924b71 to your computer and use it in GitHub Desktop.
Save xmzio/fccd29fc945de7924b71 to your computer and use it in GitHub Desktop.
My aLog and dLog macros in Swift (to abbreviate NSLog)
//
// Macros.swift
//
// Created by Xavier Muñiz on 6/12/14.
import Foundation
// dLog and aLog macros to abbreviate NSLog.
// Use like this:
//
// dLog("Log this!")
//
#if DEBUG
func dLog(message: String, filename: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) {
NSLog("[\(filename.lastPathComponent):\(line)] \(function) - \(message)")
}
#else
func dLog(message: String, filename: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) {
}
#endif
func aLog(message: String, filename: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) {
NSLog("[\(filename.lastPathComponent):\(line)] \(function) - \(message)")
}
@BryanJBryce
Copy link

I went ahead an made String into AnyObject so that I could log out a dictionary.

@bishalg
Copy link

bishalg commented Aug 27, 2015

Its sad that String in Swift 2.0 doesn't have lastPathComponent :(
We will need to use NSString if we still need that lastPathComponent.
https://forums.developer.apple.com/thread/13580

@RoLYroLLs
Copy link

With Swift 2.2 you now use #filename, #line, etc. Here's what I have to include the fix for the % and the .lastPathComponent

import Foundation

#if DEBUG
func dLog(message: String, filename: String = #file, function: String = #function, line: Int = #line) {
        NSLog("%@","[\((filename as NSString).lastPathComponent):\(line)] \(function) - \(message)")
    }
#else
    func dLog(message: String, filename: String = #file, function: String = #function, line: Int = #line) {
    }
#endif
func aLog(message: String, filename: String = #file, function: String = #function, line: Int = #line) {
    NSLog("%@","[\((filename as NSString).lastPathComponent):\(line)] \(function) - \(message)")
}

@DanielKrofchick
Copy link

I'm using it like this, a little more compact:

func dLog(message: String, filename: String = #file, function: String = #function, line: Int = #line) {
    #if DEBUG
        NSLog("[\((filename as NSString).lastPathComponent):\(line)] \(function) - \(message)")
    #endif
}

@amraboelela
Copy link

In Objective-C it was widely used as DLog, and ALog with capital D and A, so i am going to keep the same convention in Swift. in my own code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment