How to print out the method name and line number i

2020-02-07 15:48发布

Here is an example of what I want to do:

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError)
{
    let  nm =  NetworkModel()
    nm.sendlog("file name :AppDelegate , line number : 288", info: " Failed to register: \(error)")
}

current scenario i done that hard coded value line number and file name . but is it possible to programatically pick line number and file name .

标签: swift
4条回答
Fickle 薄情
2楼-- · 2020-02-07 16:34

For swift 3 and swift 4:

func printLog(_ message: String, file: String = #file, function: String = #function, line: Int = #line) {
    #if DEVELOPMENT
        let className = file.components(separatedBy: "/").last
        print(" ❌ Error ----> File: \(className ?? ""), Function: \(function), Line: \(line), Message: \(message)")
    #endif
}

// "❌ Error ----> File: classNameViewController.swift, function: functionName(), Line: 123, Message: messageError"
查看更多
Summer. ? 凉城
3楼-- · 2020-02-07 16:35

You can use #function, #file, #line

Here is the implementation of log method in swift : https://github.com/InderKumarRathore/SwiftLog

Below is the snippet

public func debugLog(object: Any, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
  #if DEBUG
    let className = (fileName as NSString).lastPathComponent
    print("<\(className)> \(functionName) [#\(lineNumber)]| \(object)\n")
  #endif
}
查看更多
做自己的国王
4楼-- · 2020-02-07 16:37
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

查看更多
▲ chillily
5楼-- · 2020-02-07 16:48
static func DLog(message: String, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) {
    print("\(file) : \(function) : \(line) : \(column) - \(message)")
}
查看更多
登录 后发表回答