是否有可能创建自定义日志功能?
这是默认的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,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或完整的日志记录系统
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。