如何从Swift中的stringWithFormat
获取NSLog()
?
例如,控制台输出为2016-05-24 18:33:31.543 MyPlayground[15578:143357] This is a test!
,那么如何获取2016-05-24 18:33:31.543
或2016-05-24 18:33:31.543 MyPlayground[15578:143357]
并将其保存到变量,而不打印到控制台?
答案 0 :(得分:4)
方括号中的数字是进程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
答案 1 :(得分:1)
我认为这非常接近:
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