2016-05-24 13 views
2

wie man die stringWithFormat von NSLog() in Swift bekommen?Wie bekomme ich "StringWithFormat" von NSLog() zu Variable in Swift?

Zum Beispiel ist die Konsolenausgabe 2016-05-24 18:33:31.543 MyPlayground[15578:143357] This is a test!, also wie Sie die oder 2016-05-24 18:33:31.543 MyPlayground[15578:143357] erhalten und speichern Sie es in einer Variablen, ohne auf Konsole drucken?

+1

Sie könnten Ihr eigenes Format-String, um die Ausgabe zu imitieren: https://developer.apple.com/ Bibliothek/Mac/Dokumentation/Cocoa/Conceptual/Strings/Artikel/formatSpecifiers.html – Alexander

+0

Ich verstehe nicht die Frage.Können Sie es mit etwas Code erklären? –

+0

'String (Format:)' ist die Swift-Wiedergabe von 'stringWithFormat' von Objective-C. – Rob

Antwort

3

Die Zahlen in den eckigen Klammern sind die Prozess-ID und die aktuelle Thread-ID, vergleiche z What are the numbers in the square brackets in NSLog() output?. Die Details können in der Implementierung von __CFLogCString() in http://opensource.apple.com//source/CF/CF-1153.18/CFUtilities.c gefunden werden.

In Swift kann dies geschehen wie folgt:

func logstring(format: String, _ arguments: CVarArgType...) -> String { 
    let fmt = NSDateFormatter() 
    fmt.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" 
    let timestamp = fmt.stringFromDate(NSDate()) 

    let pinfo = NSProcessInfo() 
    let pname = pinfo.processName 
    let pid = pinfo.processIdentifier 
    var tid = UInt64(0) 
    pthread_threadid_np(nil, &tid) 

    return "\(timestamp) \(pname)[\(pid):\(tid)] " + String(format: format, arguments: arguments) 
} 

Beispiel:

NSLog("Hello world, x=%ld", 1234) 
// 2016-05-24 19:27:35.282 MyProg[26631:1142252] Hello world, x=1234 

print(logstring("Hello world, x=%ld", 1234)) 
// 2016-05-24 19:27:35.283 MyProg[26631:1142252] Hello world, x=1234 
+1

Ich wünschte nur, "print" hat das standardmäßig getan, genauso wie NSLog. Die Zeit und den Faden zu kennen, ist nützliche Information! – matt

+0

genagelt es, congrats;) – Daniel

+0

Könnten Sie erklären, welchen Sinn haben "Format" und "Argumente" (Parameter gegeben, um zu funktionieren)? – HelloToYou

1

Ich denke, das ganz in der Nähe ist:

func interceptLog(format: String, _ arguments: CVarArgType...) -> String { 
    let fileName = (#file as NSString).lastPathComponent 
    return String(format: "\(NSDate()) \(fileName) [\(#line):\(#column)] \(format)", arguments: arguments) 
} 

Während NSLog("a: %@", "test") druckt:

2016-05-24 19:12:35.962 MyPlayground[13970:180094] a: test 

print(interceptLog("a: %@", "test")) drucken würde:

2016-05-24 17:17:12 +0000 playground60.swift [7:64] a: test 
Verwandte Themen