如何从 NSLog() 获取 "stringWithFormat" 到 Swift 中的变量?

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

如何在 Swift 中从 NSLog() 获取 stringWithFormat

例如,控制台输出是 2016-05-24 18:33:31.543 MyPlayground[15578:143357] This is a test!,那么如何获取 2016-05-24 18:33:31.5432016-05-24 18:33:31.543 MyPlayground[15578:143357] 并将其保存到变量,而不打印到控制台?

我认为这非常接近:

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

虽然 NSLog("a: %@", "test") 打印:

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

print(interceptLog("a: %@", "test")) 会打印:

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

方括号中的数字是进程id和当前 线程 ID,比较例如What are the numbers in the square brackets in NSLog() output?。 详情可参见 __CFLogCString() 的实现 在 http://opensource.apple.com//source/CF/CF-1153.18/CFUtilities.c.

在 Swift 中,可以按如下方式完成:

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