Kotlin Android打印到控制台

我需要打印一些str使用Kotlin控制台(Android Studio)。 我试过了:

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

方法。 但它似乎只适用于Java。 我应该用什么来打印使用Kotlin? 谢谢

有几种方法。

你可以使用Log.d("TAG", "message"); 例如,但首先你需要导入日志

 import android.util.Log {...} Log.d("TAG", "message") {...} 

来源: https : //developer.android.com/reference/android/util/Log.html

您也可以使用kotlin的printprintln函数。

例:

 {...} print("message") println("other message") {...} 

资料来源: https : //kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/

androidKotlin不推荐使用,而是使用Anko。

https://github.com/Kotlin/anko/blob/master/doc/ADVANCED.md#logging

 class SomeActivity : Activity(), AnkoLogger { private fun someMethod() { info("London is the capital of Great Britain") debug(5) // .toString() method will be executed warn(null) // "null" will be printed } } 

你可以使用Anko库来做到这一点。 你会有如下代码:

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

或者你也可以使用这个小的写在Kotlin库中的名为StaticLog的代码,那么你的代码将如下所示:

 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")\ 

第二个解决方案可能会更好,如果你想定义一个输出格式的日志记录方法,如:

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

或使用过滤器,例如:

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

如果您已经使用了Jake Wharton的Timber日志库,请检查此项目: https : //github.com/ajalt/timberkt 。

还请检查: 登录Kotlin和Android:AnkoLogger vs kotlin-logging

希望它会有所帮助

在这个时候(Android studio 2.3.3与kotlin插件),Log.i(TAG,“Hello World”)正常工作。 它会导入android.util.Log