加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift:格式化控制台日志

发布时间:2020-12-14 04:33:12 所属栏目:百科 来源:网络整理
导读:是否有可能创建自定义日志功能? 这是默认的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,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或完整的日志记录系统

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读