How to Print Out the Method Name and Line Number in Swift

How to print out the method name and line number in swift

Literal        Type     Value

#file String The name of the file in which it appears.
#line Int The line number on which it appears.
#column Int The column number in which it begins.
#function String The name of the declaration in which it appears.
#dsohandle UnsafeMutablePointer The dso handle.

Example

print("Function: \(#function), line: \(#line)") 

With default values in parameters you can also create a function

public func track(_ message: String, file: String = #file, function: String = #function, line: Int = #line ) { 
print("\(message) called from \(function) \(file):\(line)")
}

which can be used like this

track("enters app")

In Swift 2.1

 Literal        Type     Value

__FILE__ String The name of the file in which it appears.
__LINE__ Int The line number on which it appears.
__COLUMN__ Int The column number in which it begins.
__FUNCTION__ String The name of the declaration in which it appears.

for more info see the documentation

Log line number and method name in Swift

Swift provides some expressions in order to log, among others line number and method name:

Literal     Type    Value
#file String The name of the file in which it appears.
#line Int The line number on which it appears.
#column Int The column number in which it begins.
#function String The name of the declaration in which it appears.

For example:

func logFunctionName(string: String = #function) {
print(string)
}
func myFunction() {
logFunctionName() // Prints "myFunction()".
}

For more information, check the official documentation

Is there a way to get line number and function name in Swift language?

The Swift Language Reference defines a few "special literals" that offer this behavior:

Literal        Type     Value

#file String The name of the file in which it appears.
#line Int The line number on which it appears.
#column Int The column number in which it begins.
#function String The name of the declaration in which it appears.

How to print out the method name and line number and conditionally disable NSLog?

Here are some useful macros around NSLog I use a lot:

#ifdef DEBUG
# define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
# define DLog(...)
#endif

// ALog always displays output regardless of the DEBUG setting
#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)

The DLog macro is used to only output when the DEBUG variable is set (-DDEBUG in the projects's C flags for the debug confirguration).

ALog will always output text (like the regular NSLog).

The output (e.g. ALog(@"Hello world") ) will look like this:

-[LibraryController awakeFromNib] [Line 364] Hello world

Finding parent caller file, line number, and function in Swift

You can use default argument values. It would look something like this:

func formatError(_ except: Error,
function: StaticString = #function,
file: StaticString = #file,
line: UInt = #line) -> String {
return "[\(file).\(line):\(function)] ERROR: \(except.localizedDescription)"
}

CocoaLumberjack in Swift, how to print line number and filne name

After some more research I found that you have to create a log formatter, this log formatter is a subclass of DDDispatchQueueLogFormatter and you have to override a function that receives a DDLogMessage and returns a String, for example:

import Foundation
import CocoaLumberjack.DDDispatchQueueLogFormatter

class LogFormatter: DDDispatchQueueLogFormatter {
let dateFormatter: NSDateFormatter

override init() {
dateFormatter = NSDateFormatter()
dateFormatter.formatterBehavior = .Behavior10_4
dateFormatter.dateFormat = "HH:mm"

super.init()
}

override func formatLogMessage(logMessage: DDLogMessage!) -> String {
let dateAndTime = dateFormatter.stringFromDate(logMessage.timestamp)
return "\(dateAndTime) [\(logMessage.fileName):\(logMessage.line)]: \(logMessage.message)"
}
}

Then you just have to add your formatter like this in your AppDelegate or wherever you are setting CocaLumberJack:

DDTTYLogger.sharedInstance().logFormatter = LogFormatter()

Hope it helps someone!

How to print output of method in a struct with Swift?

At the top level of a struct or class, you're only allowed to define functions and properties. For example, your let make:String = "MINI" or func getDetails() -> String { ... } are valid top-level declarations.

You are not, however, allowed to put imperative code that doesn't define a function or property (like print("")) at the top level of a type like this.

If you were in a Swift playground, you can put imperative code at the top level of the file (not of the struct or class). So, this would be valid:

struct Car {
let make:String = "MINI"
let model:String = "COOPER"
let year:String = "2015"

var details:String {
return year + " " + make + " " + model
}
func getDetails() -> String {
return details
}
}

let myCar = Car()
print(myCar.getDetails())

Since all getDetails does is return details, it's a bit superfluous, so we could refactor to just this:

struct Car {
let make:String = "MINI"
let model:String = "COOPER"
let year:String = "2015"

var details:String {
return year + " " + make + " " + model
}
}

let myCar = Car()
print(myCar.details)

Print filename in extension

Assuming that you want to log file name and line number of the caller of that method, this is the only way. Compare Expressions (emphasis added)

When used as the default value of a function or method parameter, the special literal’s value is determined when the default value expression is evaluated at the call site.

In your case:

// Function defined in file "A.swift"
func pinToSuperview(file: String = #file) { print(file) }

// Function called in file "B.swift"
pinToSuperview()

would print "B.swift". On the other hand, #file inside the function body expands to the file name where the function is defined, so

// Function defined in file "A.swift"
func pinToSuperview() { print(#file) }

// Function called in file "B.swift"
pinToSuperview()

would print "A.swift".



Related Topics



Leave a reply



Submit