54

ロギング クラスを書き直そうとしていますが、メソッド呼び出しを追跡するために Swift ファイルでPRETTY_FUNCTIONまたは NSStringFromSelector(_cmd) を置き換える方法を知りたいですか?

4

16 に答える 16

95

Swift の特別なリテラルは次のとおりです ([swift ガイド] より)

#file 文字列表示されるファイルの名前。

#line Int表示される行番号。

#column Int開始する列番号。

#function 文字列それが現れる宣言の名前。


Swift 2.2b4 より前は、これらは

( https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html )):

__FILE__ 文字列表示されるファイルの名前。

__LINE__ Int表示される行番号。

__COLUMN__ Int開始する列番号。

__FUNCTION__ 文字列それが現れる宣言の名前。

これらは、次のようにログ ステートメントで使用できます。

println("error occurred on line \(__LINE__) in function \(__FUNCTION__)")

于 2014-06-05T00:49:23.980 に答える
63

公開したばかりの新しいライブラリをチェックしてください: https://github.com/DaveWoodCom/XCGLogger

Swift のデバッグ ロギング ライブラリです。

マクロを使用できるようにするための鍵は、#functionマクロをログ機能のデフォルト値として設定することです。コンパイラは、期待値を使用してそれらを埋めます。

func log(logMessage: String, functionName: String = #function) {
    print("\(functionName): \(logMessage)")
}

次に、次のように呼び出します。

log("my message")

そして、期待どおりに動作し、次のような結果が得られます。

whateverFunction(): my message

このしくみの詳細: https://www.cerebralgardens.com/blog/entry/2014/06/09/the-first-essential-swift-3rd-party-library-to-include-in-your-project

于 2014-06-09T22:10:35.067 に答える
5

これを試して:

class Log {
    class func msg(message: String,
        functionName:  String = __FUNCTION__, fileNameWithPath: String = __FILE__, lineNumber: Int = __LINE__ ) {
        // In the default arguments to this function:
        // 1) If I use a String type, the macros (e.g., __LINE__) don't expand at run time.
        //  "\(__FUNCTION__)\(__FILE__)\(__LINE__)"
        // 2) A tuple type, like,
        // typealias SMLogFuncDetails = (String, String, Int)
        //  SMLogFuncDetails = (__FUNCTION__, __FILE__, __LINE__) 
        //  doesn't work either.
        // 3) This String = __FUNCTION__ + __FILE__
        //  also doesn't work.

        var fileNameWithoutPath = fileNameWithPath.lastPathComponent

#if DEBUG
        let output = "\(NSDate()): \(message) [\(functionName) in \(fileNameWithoutPath), line \(lineNumber)]"
        println(output)
#endif
    }
}

次を使用してログに記録します。

let x = 100
Log.msg("My output message \(x)")
于 2015-07-31T03:22:45.077 に答える
4

これは、デバッグ モードでのみ表示されます。

func debugLog(text: String,  fileName: String = __FILE__, function: String =  __FUNCTION__, line: Int = __LINE__) {
    debugPrint("[\((fileName as NSString).lastPathComponent), in \(function)() at line: \(line)]: \(text)")
}

結果:

"[Book.swift, in addPage() at line: 33]: Page added with success"
于 2016-03-02T23:01:54.757 に答える
3

Swift 2.2 以降では、 Swift プログラミング言語ガイドLiteral Expressionsで説明されているように、を使用して指定できます。

したがってLogger、エラーが発生した場所をログに記録する関数を持つ構造体がある場合は、次のように呼び出します。

Logger().log(message, fileName: #file, functionName: #function, atLine: #line)

于 2016-04-10T15:37:20.163 に答える
2

これにより、クラスと関数名が一度に取得されます。

var name = NSStringFromClass(self.classForCoder) + "." + __FUNCTION__
于 2015-04-08T09:59:40.190 に答える