Kotlin Android print to console

前端 未结 6 954
难免孤独
难免孤独 2021-02-03 17:54

I need to print some str to console (Android Studio) using Kotlin. I\'ve tried the:

Log.v() 
Log.d() 
Log.i() 
Log.w() 
Log.e() 

methods. But i

6条回答
  •  广开言路
    2021-02-03 18:02

    You can use Anko library to do it. You would have code like below:

    class MyActivity : Activity(), AnkoLogger {
        private fun someMethod() {
            info("This is my first app and it's awesome")
            debug(1234) 
            warn("Warning")
        }
    }
    

    or you can also use this small written in Kotlin library called StaticLog then your code would looks like:

    Log.info("This is an info message")
    Log.debug("This is a debug message")
    Log.warn("This is a warning message","WithACustomTag")
    Log.error("This is an error message with an additional Exception for output", "AndACustomTag", exception )
    
    Log.logLevel = LogLevel.WARN
    Log.info("This message will not be shown")\
    

    The second solution might better if you would like to define an output format for logging method like:

    Log.newFormat {
        line(date("yyyy-MM-dd HH:mm:ss"), space, level, text("/"), tag, space(2), message, space(2), occurrence)
    }
    

    or use filters, for example:

    Log.filterTag = "filterTag"
    Log.info("This log will be filtered out", "otherTag")
    Log.info("This log has the right tag", "filterTag")
    

    If you already used Jake Wharton's Timber logging library check this project: https://github.com/ajalt/timberkt.

    Check also: Logging in Kotlin & Android: AnkoLogger vs kotlin-logging

    Hope it will help

提交回复
热议问题