是否有可能创建自定义日志功能? 这是默认的println(“hello world”)的样子: 2015-03-04 18:33:55.788 MyApp[12345:671253923] Hello World 我想输出如下内容: 18:33 MyClass myFunc [line 1] Hello World 首先,当时
这是默认的println(“hello world”)的样子:
2015-03-04 18:33:55.788 MyApp[12345:671253923] Hello World
我想输出如下内容:
18:33 MyClass > myFunc [line 1] Hello World首先,当时,您可以将当前小时和分钟作为字符串获取:
func printTime()->String{
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
return "\(hour):\(minutes)"
}
对于功能等,您可以使用Swift Literal Expressions __FILE __,__ FUNCTION__和__LINE__.
但是每次要记录时都不想设置它.所以你可以这样做:
func prettyPrint(print: String, file:String = __FILE__, functionName: String = __FUNCTION__, line:Int = __LINE__) {
println("\(printTime()) \(file) > \(functionName) [line \(line)] \(print)")
}
你这样称为prettyPrint:
prettyPrint("hey")
您将获得以下输出:
/Path/To/Your/File/MyClass.swift > hello [line 81] hey
但是,由于您只需要类的名称,因此可以使用以下函数删除路径:
func getFile(path:String = __FILE__)->String{
var parts = path.componentsSeparatedByString("/")
return parts[parts.count-1]
}
或者,正如他在回答中提到的ChikabuZ你可以直接查看课程:
let className = NSStringFromClass(self.classForCoder).pathExtension
最终功能
这里是最终的功能:
func getFile(path:String = __FILE__)->String{
var parts = path.componentsSeparatedByString("/")
return parts[parts.count-1]
}
func prettyPrint(print: String, functionName: String = __FUNCTION__, line:Int = __LINE__) {
println("\(printTime()) \(getFile()) > \(functionName) [line \(line)] \(print)")
}
func printTime()->String{
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
return "\(hour):\(minutes)"
}
结果将是:
MyClass.swift > hello [line 81] hey
你还应该注意@ emaloney对这个问题的回答.特别是那个
println()-based solutions result in output being captured by the Apple System Log (ASL).
理想情况下,切换到NSLog或完整的日志记录系统
