在 Kotlin,定义 log TAG 常数的最佳方法是什么?

我正在 Android 应用程序中创建我的第一个 Kotlin 类。通常出于日志记录的目的,我有一个名为 TAG的常量。我在 Java 中会做的是:

private static final String TAG = MyClass.class.getSimpleName();

我知道在 Kotlin 的课堂上我可以用这种方法创建 TAG:

private val TAG = MyClass::class.java.simpleName

这对于使用 Java 和 Kotlin 的项目来说是可以的,但是如果我开始一个只在 Kotlin 的新项目呢?如何定义 TAG常数?有没有更多的 Kotlin 方式,我没有这个奇怪的结构 abc 1?

40007 次浏览

I'm creating the constant as a companion object:

companion object {
val TAG = "SOME_TAG_VALUE"
}

Then, I can use it like this:

MyClass.TAG

In general constants are all caps (ex. FOO) and located in the companion object:

class MyClass {
companion object {
public const val FOO = 1


}
}

and to define the TAG field you can use:

private val TAG = MyClass::class.qualifiedName

Declare of TAG variable with val

class YourClass {
companion object {
//if use java and kotlin both in project
//private val TAG = MyClass::class.java.simpleName


//if use only kotlin in project
private val TAG = YourClass::class.simpleName
}
}

Use the variable like

Log.d(YourClass.TAG, "Your message");
//or
Log.e(TAG, "Your message");

I found a way which is more "copy-paste"-able, since it doesn't require you to type the name of your class:

package com.stackoverflow.mypackage


class MyClass
{
companion object {
val TAG = this::class.toString().split(".").last().dropLast(10)
}
}

It's not the most elegant solution but it works.

this::class.toString().split(".").last() will give you "com.stackoverflow.mypackage.MyClass$Companion" so you need the dropLast(10) to remove $Companion.

Alternatively you can do this:

package com.stackoverflow.mypackage


class MyClass
{
val TAG = this::class.simpleName
}

But then the TAG member variable is no longer "static" and doesn't follow the recommended naming conventions.

AnkoLogger uses an interface to define the log tag.

interface AnkoLogger {
/**
* The logger tag used in extension functions for the [AnkoLogger].
* Note that the tag length should not be more than 23 symbols.
*/
val loggerTag: String
get() = getTag(javaClass)
}
private fun getTag(clazz: Class<*>): String {
val tag = clazz.simpleName
return if (tag.length <= 23) {
tag
} else {
tag.substring(0, 23)
}
}
inline fun AnkoLogger.info(message: () -> Any?) {
val tag = loggerTag
if (Log.isLoggable(tag, Log.INFO)) {
Log.i(tag, message()?.toString() ?: "null")
}
}

You can use it like this:

class MyClass : AnkoLogger {
fun someFun(){
info("logging info")
}
}

Maybe AnkoLogger can give you some ideas to implement a custom logging tool.

You can define your TAG by @JvmField as below:

companion object {
@JvmField val TAG: String = MyClass::class.java.simpleName
}

For more details, you can read this article : Kotlin's hidden costs

Updated answer with Kotlin 1.2.20

class MyClass {
companion object {


@JvmField
public val FOO = 1
}
}

uses

MyClass.FOO

Commonly suggested approach of using the companion object generates extra static final instance of a companion class and thus is bad performance and memory-wise.

The best way (IMHO)

Define a log tag as a top-level constant, thus only extra class is generated (MyClassKt), but compared to companion object there will be no static final instance of it (and no instance whatsoever):

private const val TAG = "MyLogTag"


class MyClass {


fun logMe() {
Log.w(TAG, "Message")
}
}

Another option

Use a normal val. Though this looks unusual to see a log tag not as an all-uppercase constant, this will not generate any classes and has least overhead.

class MyClass {


private val tag = "myLogTag"


fun logMe() {
Log.w(tag, "Message")
}
}

Simply doing the following worked for me.

private val TAG = this::class.java.simpleName

I created some Log extension functions to avoid declaring the log tag as we did in Java (maybe less performant, but given that we are talking about logging this should be acceptable IMO). The approach uses reified type parameters and other Kotlin goodies to retrieve the class simple name. Here is a basic example:

inline fun <reified T> T.logi(message: String) =
Log.i(T::class.java.simpleName, message)

You can find a more elaborated gist here

In Android Studio, the usual way to rename something is to right-click the name, select Refactor->Rename. So, I think it's fine to do something like this,

class MyClass {
companion object {
private const LOG_TAG = "MyClass"
}
}

because if you rename the class MyClass like I described, then the IDE will suggest renaming your LOG_TAG String as well.

Ultimately there are pros and cons of using this method vs. other methods. Because LOG_TAG is a String, there's no need to import the kotlin-reflect.jar, as you would if you set LOG_TAG equal to MyClass::class.simpleName. Also because the variable is declared as a compile-time constant with the const keyword, the generated bytecode is smaller since it doesn't need to generate more hidden getters, as described in this article.

In Kotlin you could create an extension, and call tag as a method call instead. This would mean you'd never have to define it inside each class, we can construct it dynamically each time we call the method:

inline fun <reified T> T.TAG(): String = T::class.java.simpleName

This extension allows us to use TAG in any class

val Any.TAG: String
get() {
val tag = javaClass.simpleName
return if (tag.length <= 23) tag else tag.substring(0, 23)
}


//usage
Log.e(TAG,"some value")

It it also validated to work as an Android valid Log tag.

I Like TAG to be an extension function as suggested by Fredy Mederos.

extending his answer to support anonymous classes :

 /**
* extension function to provide TAG value
*/
val Any.TAG: String
get() {
return if (!javaClass.isAnonymousClass) {
val name = javaClass.simpleName
if (name.length <= 23) name else name.substring(0, 23)// first 23 chars
} else {
val name = javaClass.name
if (name.length <= 23) name else name.substring(name.length - 23, name.length)// last 23 chars
}
}

The best way to log (imho) is using Timber: https://github.com/JakeWharton/timber

But if you don't want to use library then

TAG can be defined as an inlined extension property (e.g. in Extensions.kt):

inline val <reified T> T.TAG: String
get() = T::class.java.simpleName

Some more extensions to not to write TAG all the time in Log.d(TAG, ""):

inline fun <reified T> T.logv(message: String) = Log.v(TAG, message)
inline fun <reified T> T.logi(message: String) = Log.i(TAG, message)
inline fun <reified T> T.logw(message: String) = Log.w(TAG, message)
inline fun <reified T> T.logd(message: String) = Log.d(TAG, message)
inline fun <reified T> T.loge(message: String) = Log.e(TAG, message)

And then you can use them in any class:

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
logd("Activity created")
}

You can try this:

companion object {
val TAG = ClearCacheTask::class.java.simpleName as String
}

Here is my extension function in kotlin, just add it in your extensions file.

val Any.TAG: String
get() {
return if (!javaClass.isAnonymousClass) {
val name = javaClass.simpleName
if (name.length <= 23 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) name else
name.substring(0, 23)// first 23 chars
} else {
val name = javaClass.name
if (name.length <= 23 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
name else name.substring(name.length - 23, name.length)// last 23 chars
}
}

Then you can use TAG in any class like below:

Log.d(TAG, "country list")

I have defined an interface, which defines TAG as a property with default getter implementation. The interface can be either "implemented" by a class but also by its companion object:

//Prefix allows easier filtering in LogCat
private const val PREFIX = "somePrefix.";


interface HasLogTag {
val TAG: String
get() {
val name = javaClass.canonicalName?.removeSuffix(".Companion")?.substringAfterLast(".")
return "$PREFIX${name}"
}
}

The interface is used as follows:

import yourPackage.HasLogTag
....
class MyClass : HasLogTag {
...
//Alternatively: Let the companion object "implement" the interface
companion object : HasLogTag {
...
Log.e(TAG, "Some Info)
}

As the getter is called on every usage, there is however no advantage in defining the TAG for the companion object.

Note: In a previous version, I used reflection to find out, whether the class itself or the companion object defines the interface.

This however seemed to slow down heavily the startup of my app.