HelloToYou HelloToYou - 10 months ago 104
Swift Question

How to get "stringWithFormat" from NSLog() to Variable in Swift?

how to get the

in Swift?

For example the Console Output is
2016-05-24 18:33:31.543 MyPlayground[15578:143357] This is a test!
, so how to get the
2016-05-24 18:33:31.543
2016-05-24 18:33:31.543 MyPlayground[15578:143357]
and save it to a Variable, without printing to Console?


The numbers in the square brackets are the process id and the current thread id, compare e.g. What are the numbers in the square brackets in NSLog() output?. The details can be found in the implementation of __CFLogCString() in http://opensource.apple.com//source/CF/CF-1153.18/CFUtilities.c.

In Swift this can be done as follows:

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)


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