2016-07-22 115 views
4

我需要使用Kotlin打印一些str到控制檯(Android Studio)。 我試過了:Kotlin Android打印到控制檯

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

方法。但它似乎只適用於Java。 我應該使用Kotlin打印什麼? 謝謝

+0

任何Java方法也可以與Kotlin一起使用。 「這似乎起作用」是什麼意思? – yole

回答

4

有一對夫婦的方式。

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

import android.util.Log 

{...} 

Log.d("TAG", "message") 

{...} 

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

您還可以使用科特林的打印的println功能。

例子:

{...} 

print("message") 

println("other message") 

{...} 

來源:https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/

+5

Kotlin的print和println函數不會打印到Android日誌中。 – yole

+1

確實如此,它們會按照設置爲源的文檔中所述的那樣打印到標準輸出。但問題實際上是打印到控制檯,不一定是android日誌。我想它仍然適合=) – Ramalus

2

androidKotlin is deprecated and use Anko instead。

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 
    } 
} 
+1

正如鏈接庫的自述文件所述,它已被棄用。應該使用[Anko](https://github.com/kotlin/anko)。 – yole

+0

恐怕我沒有注意到那部分。我將更新答案 –

1

您可以使用Anko庫來做到這一點。你將不得不像下面的代碼:

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

,或者您也可以使用這個小寫在科特林庫調用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

檢查也:Logging in Kotlin & Android: AnkoLogger vs kotlin-logging

希望這將有助於

0

在這一刻(機器人工作室2.3.3科特林插件),Log.i(TAG,的 「Hello World」)只是工作。它將導入android.util.Log