How to make proguard keep kotlinx serializers for objects? - proguard

i have a kotlin class and an object
#Serializable
#SerialName("Cl")
class Cl(...)
#Serializable
#SerialName("Obj")
object Obj
and my proguard is configured like this
-keepclassmembers class kotlinx.serialization.json.** {
*** Companion;
}
-keepclasseswithmembers class kotlinx.serialization.json.** {
kotlinx.serialization.KSerializer serializer(...);
}
-keepclasseswithmembers class .** {
kotlinx.serialization.KSerializer serializer(...);
}
-keep,includedescriptorclasses class my.package.**$$serializer { *; }
but, while the serializer of the class is kept, the serializer of the object is not.
here is the mapping of the class:
Cl -> Cl:
...
...
67:67:void <init>(... ,kotlinx.serialization.internal.SerializationConstructorMarker) -> <init>
70:75:void <init>(...) -> <init>
67:67:void write$Self(Cl,kotlinx.serialization.encoding.CompositeEncoder,kotlinx.serialization.descriptors.SerialDescriptor) -> e
Cl$$serializer -> Cl$$serializer:
...
67:75:void <clinit>() -> <clinit>
67:67:void <init>() -> <init>
67:67:kotlinx.serialization.KSerializer[] childSerializers() -> childSerializers
67:67:Cl deserialize(kotlinx.serialization.encoding.Decoder) -> deserialize
67:67:java.lang.Object deserialize(kotlinx.serialization.encoding.Decoder) -> deserialize
67:67:void serialize(kotlinx.serialization.encoding.Encoder,Cl) -> serialize
67:67:void serialize(kotlinx.serialization.encoding.Encoder,java.lang.Object) -> serialize
67:67:kotlinx.serialization.KSerializer[] typeParametersSerializers() -> typeParametersSerializers
Cl$Companion -> Cl$Companion:
...
67:67:void <init>() -> <init>
67:67:kotlinx.serialization.KSerializer serializer() -> serializer
and here is the mapping of the object:
Obj -> Obj:
...
Obj INSTANCE -> n
kotlin.Lazy $cachedSerializer$delegate -> o
...
47:47:kotlin.Lazy get$cachedSerializer$delegate() -> e
47:47:kotlinx.serialization.KSerializer serializer() -> serializer
Obj$$cachedSerializer$delegate$1 -> Obj$a:
...
Obj$$cachedSerializer$delegate$1 INSTANCE -> l
47:47:kotlinx.serialization.KSerializer invoke() -> a
47:47:java.lang.Object invoke() -> m
...
this obfuscation causes a crash (only when obfuscated, only for object) when using:
polymorphic(...) {
subclass(Obj::class)
}
Serializer for class 'Obj' is not found. Mark the class as #Serializable or provide the serializer explicitly.
How can i tell Proguard to keep the serializer for objects?

There is documentation available on how to configure ProGuard, which does not seem to match the configuration you are using.
Use that and you should be good to go.
Purely informational, since the above already answers your question: serializer lookup at runtime for object is different and happens through INSTANCE. The relevant part from the docs.
# Keep `INSTANCE.serializer()` of serializable objects.
-if #kotlinx.serialization.Serializable class ** {
public static ** INSTANCE;
}
-keepclassmembers class <1> {
public static <1> INSTANCE;
kotlinx.serialization.KSerializer serializer(...);
}

Related

Kotlin serialization: nested polymorphic module

Recently I've been trying to implement Kotlinx Serialization for polymorphic class hierarchy. I used this guide, however my example was a bit more complex. I had the following class structure:
#Serializable
open class Project(val name: String)
#Serializable
#SerialName("owned")
open class OwnedProject(val owner: String) : Project("kotlin")
#Serializable
#SerialName("owned_owned")
class OwnedOwnedProject(val ownerOwner: String) : OwnedProject("kotlinx.coroutines")
And was trying to deserialize OwnedOwnedProject instance using following code:
val module = SerializersModule {
polymorphic(Project::class) {
polymorphic(OwnedProject::class) {
subclass(OwnedOwnedProject::class)
}
}
}
val format = Json { serializersModule = module }
fun main() {
val str = "{\"type\":\"owned_owned\",\"name\":\"kotlin\",\"owner\":\"kotlinx.coroutines\",\"ownerOwner\":\"kotlinx.coroutines.launch\"}"
val obj = format.decodeFromString(PolymorphicSerializer(Project::class), str)
println(obj)
}
However whatever combinations of SerializersModule definition I tried, it always ended up with kotlinx.serialization.json.internal.JsonDecodingException: Polymorphic serializer was not found for class discriminator 'owned_owned' error.
Could you please give me a hint: how to implement SerializersModule for given class structure (deeper than two)? Am I missing something?
It seems you would need to register OwnedOwnedProject directly under Project as well, so the serializer knows it's a possible subclass:
val module = SerializersModule {
polymorphic(Project::class) {
subclass(OwnedOwnedProject::class)
}
polymorphic(OwnedProject::class) {
subclass(OwnedOwnedProject::class)
}
}

How do I create a "Class" instance in Kotlin with specific type parameters?

I have this parent class and this child class:
abstract class ParentClass<T> {
protected abstract val dataClass: Class<T>
}
class ChildClass<K, V> : ParentClass<Map<K, V>>() {
override val dataClass: Class<Map<K, V>>
get() = HashMap::class.java // compilation error, invalid return type
}
I want the child class to implement the dataClass member such that I can use it to create instances of type T later on:
T data = dataClass.newInstance()
However, the return type for my implementation of dataClass is not valid in this context, so it doesn't compile:
Class<Map<K, V>> // required
Class<HashMap<*, *>> // found
Is there any way to specify the type parameters for the Class instance, or a different solution altogether to this problem? I realize I could replace the parent member with Class<*>, but I want something that is type safe.
I just ended up modifying the member into a function to generate a new instance, and added a second lazy member to get the class by creating a temporary instance:
abstract class ParentClass<T : Any> {
protected abstract fun createDataInstance(): T
private val dataClass: Class<T> by lazy {
createDataInstance()::class.java as Class<T>
}
}
class ChildClass<K, V> : ParentClass<Map<K, V>>() {
override fun createDataInstance(): Map<K, V> = HashMap()
}
// snippet (Java)
ChildClass<Integer, Integer> childClass = new ChildClass<>();
Map<Integer, Integer> instance = childClass.getDataInstance();
instance.put(0, 1);
System.out.println("Child instance #1: " + instance);
System.out.println("Child instance class " + childClass.getDataClass());
System.out.println("Child instance #2: " + childClass.getDataInstance());
// output (Java)
Child instance #1: {0=1}
Child instance class class java.util.HashMap
Child instance #2: {}

How to obtain all subclasses of a given sealed class?

Recently we upgraded one of our enum class to sealed class with objects as sub-classes so we can make another tier of abstraction to simplify code. However we can no longer get all possible subclasses through Enum.values() function, which is bad because we heavily rely on that functionality. Is there a way to retrieve such information with reflection or any other tool?
PS: Adding them to a array manually is unacceptable. There are currently 45 of them, and there are plans to add more.
This is how our sealed class looks like:
sealed class State
object StateA: State()
object StateB: State()
object StateC: State()
....// 42 more
If there is an values collection, it will be in this shape:
val VALUES = setOf(StateA, StateB, StateC, StateC, StateD, StateE,
StateF, StateG, StateH, StateI, StateJ, StateK, StateL, ......
Naturally no one wants to maintain such a monster.
In Kotlin 1.3+ you can use sealedSubclasses.
In prior versions, if you nest the subclasses in your base class then you can use nestedClasses:
Base::class.nestedClasses
If you nest other classes within your base class then you'll need to add filtering. e.g.:
Base::class.nestedClasses.filter { it.isFinal && it.isSubclassOf(Base::class) }
Note that this gives you the subclasses and not the instances of those subclasses (unlike Enum.values()).
With your particular example, if all of your nested classes in State are your object states then you can use the following to get all of the instances (like Enum.values()):
State::class.nestedClasses.map { it.objectInstance as State }
And if you want to get really fancy you can even extend Enum<E: Enum<E>> and create your own class hierarchy from it to your concrete objects using reflection. e.g.:
sealed class State(name: String, ordinal: Int) : Enum<State>(name, ordinal) {
companion object {
#JvmStatic private val map = State::class.nestedClasses
.filter { klass -> klass.isSubclassOf(State::class) }
.map { klass -> klass.objectInstance }
.filterIsInstance<State>()
.associateBy { value -> value.name }
#JvmStatic fun valueOf(value: String) = requireNotNull(map[value]) {
"No enum constant ${State::class.java.name}.$value"
}
#JvmStatic fun values() = map.values.toTypedArray()
}
abstract class VanillaState(name: String, ordinal: Int) : State(name, ordinal)
abstract class ChocolateState(name: String, ordinal: Int) : State(name, ordinal)
object StateA : VanillaState("StateA", 0)
object StateB : VanillaState("StateB", 1)
object StateC : ChocolateState("StateC", 2)
}
This makes it so that you can call the following just like with any other Enum:
State.valueOf("StateB")
State.values()
enumValueOf<State>("StateC")
enumValues<State>()
UPDATE
Extending Enum directly is no longer supported in Kotlin. See
Disallow to explicitly extend Enum class : KT-7773.
With Kotlin 1.3+ you can use reflection to list all sealed sub-classes without having to use nested classes: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-class/sealed-subclasses.html
I asked for some feature to achieve the same without reflection: https://discuss.kotlinlang.org/t/list-of-sealed-class-objects/10087
Full example:
sealed class State{
companion object {
fun find(state: State) =
State::class.sealedSubclasses
.map { it.objectInstance as State}
.firstOrNull { it == state }
.let {
when (it) {
null -> UNKNOWN
else -> it
}
}
}
object StateA: State()
object StateB: State()
object StateC: State()
object UNKNOWN: State()
}
A wise choice is using ServiceLoader in kotlin. and then write some providers to get a common class, enum, object or data class instance. for example:
val provides = ServiceLoader.load(YourSealedClassProvider.class).iterator();
val subInstances = providers.flatMap{it.get()};
fun YourSealedClassProvider.get():List<SealedClass>{/*todo*/};
the hierarchy as below:
Provider SealedClass
^ ^
| |
-------------- --------------
| | | |
EnumProvider ObjectProvider ObjectClass EnumClass
| |-------------------^ ^
| <uses> |
|-------------------------------------------|
<uses>
Another option, is more complicated, but it can meet your needs since sealed classes in the same package. let me tell you how to archive in this way:
get the URL of your sealed class, e.g: ClassLoader.getResource("com/xxx/app/YourSealedClass.class")
scan all jar entry/directory files in parent of sealed class URL, e.g: jar://**/com/xxx/app or file://**/com/xxx/app, and then find out all the "com/xxx/app/*.class" files/entries.
load filtered classes by using ClassLoader.loadClass(eachClassName)
check the loaded class whether is a subclass of your sealed class
decide how to get the subclass instance, e.g: Enum.values(), object.INSTANCE.
return all of instances of the founded sealed classes
If you want use it at child class try this.
open class BaseSealedClass(val value: String, val name: Int) {
companion object {
inline fun<reified T:BaseSealedClass> valueOf(value: String): T? {
return T::class.nestedClasses
.filter { clazz -> clazz.isSubclassOf(T::class) }
.map { clazz -> clazz.objectInstance }
.filterIsInstance<T>()
.associateBy { it.value }[value]
}
inline fun<reified T:BaseSealedClass> values():List<T> =
T::class.nestedClasses
.filter { clazz -> clazz.isSubclassOf(T::class) }
.map { clazz -> clazz.objectInstance }
.filterIsInstance<T>()
}
}
#Stable
sealed class Theme(value: String, name: Int): BaseSealedClass(value, name) {
object Auto: Theme(value = "auto", name = R.string.setting_general_theme_auto)
object Light: Theme(value= "light", name = R.string.setting_general_theme_light)
object Dark: Theme(value= "dark", name = R.string.setting_general_theme_dark)
companion object {
fun valueOf(value: String): Theme? = BaseSealedClass.valueOf(value)
fun values():List<Theme> = BaseSealedClass.values()
}
}
For a solution without reflection this is a library that supports generating a list of types to sealed classes at compile time:
https://github.com/livefront/sealed-enum
The example in the docs
sealed class Alpha {
object Beta : Alpha()
object Gamma : Alpha()
#GenSealedEnum
companion object
}
will generate the following object:
object AlphaSealedEnum : SealedEnum<Alpha> {
override val values: List<Alpha> = listOf(
Alpha.Beta,
Alpha.Gamma
)
override fun ordinalOf(obj: Alpha): Int = when (obj) {
Alpha.Beta -> 0
Alpha.Gamma -> 1
}
override fun nameOf(obj: AlphaSealedEnum): String = when (obj) {
Alpha.Beta -> "Alpha_Beta"
Alpha.Gamma -> "Alpha_Gamma"
}
override fun valueOf(name: String): AlphaSealedEnum = when (name) {
"Alpha_Beta" -> Alpha.Beta
"Alpha_Gamma" -> Alpha.Gamma
else -> throw IllegalArgumentException("""No sealed enum constant $name""")
}
}
The short version is
State::class.sealedSubclasses.mapNotNull { it.objectInstance }

Incompatible types: A and kotlin.reflect.KType

I want to check that function has parameter of A type use the following code:
import kotlin.reflect.*
import javafx.event.ActionEvent
interface IA {}
class A {}
class B {
fun test(a: A, ia: IA, event: ActionEvent) {
println(a)
println(ia)
println(event)
}
}
fun main(args: Array<String>) {
for (function in B::class.declaredMemberFunctions) {
for (parameter in function.parameters) {
when (parameter.type) {
is IA -> println("Has IA interface parameter.")
is ActionEvent -> println("Has ActionEvent class parameter.")
is A -> println("Has A class parameter.") // <---- compilation error in this line
}
}
}
}
but when I try to compile it I see the following error:
> Error:(20, 19) Incompatible types: A and kotlin.reflect.KType
Questions:
Why compiler don't raise error for IA interface and ActionEvent Java class?
Why compiller raise error for A class?
How to check that function has argument of A type?
The thing is you're trying to check if KType is A, which is always false. And the compiler knows it and raises a compilation error. But IA is an interface a class that implements KType can possibly implement this interface too so there's no compilation error. ActionEvent is an open class so it's subtype can implement KType - no compilation error either.
What you should do to check if the parameter type is some class or some interface is the following.
when (parameter.type.javaType) {
IA::class.javaClass -> println("Has IA interface parameter.")
ActionEvent::class.javaClass -> println("Has ActionEvent class parameter.")
A::class.javaClass -> println("Has A class parameter.")
}
First, you are using the wrong operator. is checks if an instance of something is a given class. You have no instance. You instead have a KType that you are trying to check if it is the instance of a class A, or IA or ActionEvent, it isn't.
So you need to use a different operator, which is to check if they are equal or call the method isAssignableFrom(). And then you need to check that the two things you are comparing are the right datatypes and do what you expect.
In another answer, #Michael says you can just treat a Type and Class the same for equality, that isn't always true; not that simple. Sometimes a Type is a Class but sometimes it is a ParameterizedType, GenericArrayType, TypeVariable, or WildcardType which are not comparable with equals. So that approach is wrong if you ever have a parameter to the method that uses generics it breaks.
Here is a version that does not support generics in that if generics are used in the parameter, they will not match. This also compares KTypeusing equality, which means it does not work for inherited classes matching against a superclass or interface. But the most simple is:
when (parameter.type) {
IA::class.defaultType -> println("Has IA interface parameter.")
ActionEvent::class.defaultType -> println("Has ActionEvent class parameter.")
A::class.defaultType -> println("Has A class parameter.")
}
This breaks if For example if class A had generic parameter T so you wanted to check a parameter that is A<String> or A<Monkey> you will not match A::class.defaultType (FALSE!!!). Or if you tried to compare array types, again will not match.
To fix this generics problem, we need to also erase the paramter.type you are checking. We need a helper function to do that.
Here is one copied from the Klutter library that takes a KType and erases the generics to make a KClass. You will need the kotlin-reflect dependency to use this code. You can remove the kotlin-refect dependency by only working with Java Class and not using KClass anywhere directly. Some other code will have to change.
With the following extension function:
fun KType.erasedType(): KClass<*> {
return this.javaType.erasedType().kotlin
}
#Suppress("UNCHECKED_CAST")
fun Type.erasedType(): Class<*> {
return when (this) {
is Class<*> -> this as Class<Any>
is ParameterizedType -> this.getRawType().erasedType()
is GenericArrayType -> {
// getting the array type is a bit trickier
val elementType = this.getGenericComponentType().erasedType()
val testArray = java.lang.reflect.Array.newInstance(elementType, 0)
testArray.javaClass
}
is TypeVariable<*> -> {
// not sure yet
throw IllegalStateException("Not sure what to do here yet")
}
is WildcardType -> {
this.getUpperBounds()[0].erasedType()
}
else -> throw IllegalStateException("Should not get here.")
}
}
You can now write your code more simply as:
when (parameter.type.erasedType()) {
IA::class-> println("Has IA interface parameter.")
ActionEvent::class -> println("Has ActionEvent class parameter.")
A::class -> println("Has A class parameter.")
}
So generics are ignored and this works comparing the raw erased class against each other; but again without inheritance.
To support inheritance you can use this version slightly modified. You need a different form of when expression and a helper function:
fun assignCheck(ancestor: KClass<*>, checkType: KType): Boolean =
ancestor.java.isAssignableFrom(checkType.javaType.erasedType())
Then the when expression changed to:
when {
assignCheck(IA::class, parameter.type) -> println("Has IA interface parameter.")
assignCheck(ActionEvent::class, parameter.type) -> println("Has ActionEvent class parameter.")
assignCheck(A::class, parameter.type) -> println("Has A class parameter.")
}
Extra credit, comparing full generics:
To compare full generics we need to convert everything to something that we can compare that still has generics. The easiest is to get everything into a Java Type since it is harder to get everything into a KType. First we need a TypeReference type class, we'll steal this from Klutter library as well:
abstract class TypeReference<T> protected constructor() {
val type: Type by lazy {
javaClass.getGenericSuperclass().let { superClass ->
if (superClass is Class<*>) {
throw IllegalArgumentException("Internal error: TypeReference constructed without actual type information")
}
(superClass as ParameterizedType).getActualTypeArguments()[0]
}
}
}
Now a quick extension method to use this:
inline fun <reified T: Any> ft(): Type = object:TypeReference<T>(){}.type
And then our when expression can be more detailed with generics:
for (parameter in function.parameters) {
when (parameter.type.javaType) {
ft<IA>() -> println("Has IA interface parameter.")
ft<ActionEvent>() -> println("Has ActionEvent class parameter.")
ft<A<String>>() -> println("Has A<String> class parameter.") // <---- compilation error in this line
ft<A<Monkey>>() -> println("Has A<Monkey> class parameter.") // <---- compilation error in this line
}
}
But in doing this, we broke inheritance checking again. And we don't really check covariance of the generics (they themselves could have superclass checks).
Double Extra Credit, what about inheritance AND generics?!?
Um, this isn't so much fun. I'll have to think about that one a bit, maybe add it to Klutter later. It is kinda complicated.

Idiomatic way of logging in Kotlin

Kotlin doesn't have the same notion of static fields as used in Java. In Java, the generally accepted way of doing logging is:
public class Foo {
private static final Logger LOG = LoggerFactory.getLogger(Foo.class);
}
Question is what is the idiomatic way of performing logging in Kotlin?
In the majority of mature Kotlin code, you will find one of these patterns below. The approach using Property Delegates takes advantage of the power of Kotlin to produce the smallest code.
Note: the code here is for java.util.Logging but the same theory applies to any logging library
Static-like (common, equivalent of your Java code in the question)
If you cannot trust in the performance of that hash lookup inside the logging system, you can get similar behavior to your Java code by using a companion object which can hold an instance and feel like a static to you.
class MyClass {
companion object {
val LOG = Logger.getLogger(MyClass::class.java.name)
}
fun foo() {
LOG.warning("Hello from MyClass")
}
}
creating output:
Dec 26, 2015 11:28:32 AM org.stackoverflow.kotlin.test.MyClass foo
INFO: Hello from MyClass
More on companion objects here: Companion Objects ... Also note that in the sample above MyClass::class.java gets the instance of type Class<MyClass> for the logger, whereas this.javaClass would get the instance of type Class<MyClass.Companion>.
Per Instance of a Class (common)
But, there is really no reason to avoid calling and getting a logger at the instance level. The idiomatic Java way you mentioned is outdated and based on fear of performance, whereas the logger per class is already cached by almost any reasonable logging system on the planet. Just create a member to hold the logger object.
class MyClass {
val LOG = Logger.getLogger(this.javaClass.name)
fun foo() {
LOG.warning("Hello from MyClass")
}
}
creating output:
Dec 26, 2015 11:28:44 AM org.stackoverflow.kotlin.test.MyClass foo
INFO: Hello from MyClass
You can performance test both per instance and per class variations and see if there is a realistic difference for most apps.
Property Delegates (common, most elegant)
Another approach, which is suggested by #Jire in another answer, is to create a property delegate, which you can then use to do the logic uniformly in any other class that you want. There is a simpler way to do this since Kotlin provides a Lazy delegate already, we can just wrap it in a function. One trick here is that if we want to know the type of the class currently using the delegate, we make it an extension function on any class:
fun <R : Any> R.logger(): Lazy<Logger> {
return lazy { Logger.getLogger(unwrapCompanionClass(this.javaClass).name) }
}
// see code for unwrapCompanionClass() below in "Putting it all Together section"
This code also makes sure that if you use it in a Companion Object that the logger name will be the same as if you used it on the class itself. Now you can simply:
class Something {
val LOG by logger()
fun foo() {
LOG.info("Hello from Something")
}
}
for per class instance, or if you want it to be more static with one instance per class:
class SomethingElse {
companion object {
val LOG by logger()
}
fun foo() {
LOG.info("Hello from SomethingElse")
}
}
And your output from calling foo() on both of these classes would be:
Dec 26, 2015 11:30:55 AM org.stackoverflow.kotlin.test.Something foo
INFO: Hello from Something
Dec 26, 2015 11:30:55 AM org.stackoverflow.kotlin.test.SomethingElse foo
INFO: Hello from SomethingElse
Extension Functions (uncommon in this case because of "pollution" of Any namespace)
Kotlin has a few hidden tricks that let you make some of this code even smaller. You can create extension functions on classes and therefore give them additional functionality. One suggestion in the comments above was to extend Any with a logger function. This can create noise anytime someone uses code-completion in their IDE in any class. But there is a secret benefit to extending Any or some other marker interface: you can imply that you are extending your own class and therefore detect the class you are within. Huh? To be less confusing, here is the code:
// extend any class with the ability to get a logger
fun <T: Any> T.logger(): Logger {
return Logger.getLogger(unwrapCompanionClass(this.javaClass).name)
}
Now within a class (or companion object), I can simply call this extension on my own class:
class SomethingDifferent {
val LOG = logger()
fun foo() {
LOG.info("Hello from SomethingDifferent")
}
}
Producing output:
Dec 26, 2015 11:29:12 AM org.stackoverflow.kotlin.test.SomethingDifferent foo
INFO: Hello from SomethingDifferent
Basically, the code is seen as a call to extension Something.logger(). The problem is that the following could also be true creating "pollution" on other classes:
val LOG1 = "".logger()
val LOG2 = Date().logger()
val LOG3 = 123.logger()
Extension Functions on Marker Interface (not sure how common, but common model for "traits")
To make the use of extensions cleaner and reduce "pollution", you could use a marker interface to extend:
interface Loggable {}
fun Loggable.logger(): Logger {
return Logger.getLogger(unwrapCompanionClass(this.javaClass).name)
}
Or even make the method part of the interface with a default implementation:
interface Loggable {
public fun logger(): Logger {
return Logger.getLogger(unwrapCompanionClass(this.javaClass).name)
}
}
And use either of these variations in your class:
class MarkedClass: Loggable {
val LOG = logger()
}
Producing output:
Dec 26, 2015 11:41:01 AM org.stackoverflow.kotlin.test.MarkedClass foo
INFO: Hello from MarkedClass
If you wanted to force the creation of a uniform field to hold the logger, then while using this interface you could easily require the implementer to have a field such as LOG:
interface Loggable {
val LOG: Logger // abstract required field
public fun logger(): Logger {
return Logger.getLogger(unwrapCompanionClass(this.javaClass).name)
}
}
Now the implementer of the interface must look like this:
class MarkedClass: Loggable {
override val LOG: Logger = logger()
}
Of course, an abstract base class can do the same, having the option of both the interface and an abstract class implementing that interface allows flexibility and uniformity:
abstract class WithLogging: Loggable {
override val LOG: Logger = logger()
}
// using the logging from the base class
class MyClass1: WithLogging() {
// ... already has logging!
}
// providing own logging compatible with marker interface
class MyClass2: ImportantBaseClass(), Loggable {
// ... has logging that we can understand, but doesn't change my hierarchy
override val LOG: Logger = logger()
}
// providing logging from the base class via a companion object so our class hierarchy is not affected
class MyClass3: ImportantBaseClass() {
companion object : WithLogging() {
// we have the LOG property now!
}
}
Putting it All Together (A small helper library)
Here is a small helper library to make any of the options above easy to use. It is common in Kotlin to extend API's to make them more to your liking. Either in extension or top-level functions. Here is a mix to give you options for how to create loggers, and a sample showing all variations:
// Return logger for Java class, if companion object fix the name
fun <T: Any> logger(forClass: Class<T>): Logger {
return Logger.getLogger(unwrapCompanionClass(forClass).name)
}
// unwrap companion class to enclosing class given a Java Class
fun <T : Any> unwrapCompanionClass(ofClass: Class<T>): Class<*> {
return ofClass.enclosingClass?.takeIf {
ofClass.enclosingClass.kotlin.companionObject?.java == ofClass
} ?: ofClass
}
// unwrap companion class to enclosing class given a Kotlin Class
fun <T: Any> unwrapCompanionClass(ofClass: KClass<T>): KClass<*> {
return unwrapCompanionClass(ofClass.java).kotlin
}
// Return logger for Kotlin class
fun <T: Any> logger(forClass: KClass<T>): Logger {
return logger(forClass.java)
}
// return logger from extended class (or the enclosing class)
fun <T: Any> T.logger(): Logger {
return logger(this.javaClass)
}
// return a lazy logger property delegate for enclosing class
fun <R : Any> R.lazyLogger(): Lazy<Logger> {
return lazy { logger(this.javaClass) }
}
// return a logger property delegate for enclosing class
fun <R : Any> R.injectLogger(): Lazy<Logger> {
return lazyOf(logger(this.javaClass))
}
// marker interface and related extension (remove extension for Any.logger() in favour of this)
interface Loggable {}
fun Loggable.logger(): Logger = logger(this.javaClass)
// abstract base class to provide logging, intended for companion objects more than classes but works for either
abstract class WithLogging: Loggable {
val LOG = logger()
}
Pick whichever of those you want to keep, and here are all of the options in use:
class MixedBagOfTricks {
companion object {
val LOG1 by lazyLogger() // lazy delegate, 1 instance per class
val LOG2 by injectLogger() // immediate, 1 instance per class
val LOG3 = logger() // immediate, 1 instance per class
val LOG4 = logger(this.javaClass) // immediate, 1 instance per class
}
val LOG5 by lazyLogger() // lazy delegate, 1 per instance of class
val LOG6 by injectLogger() // immediate, 1 per instance of class
val LOG7 = logger() // immediate, 1 per instance of class
val LOG8 = logger(this.javaClass) // immediate, 1 instance per class
}
val LOG9 = logger(MixedBagOfTricks::class) // top level variable in package
// or alternative for marker interface in class
class MixedBagOfTricks : Loggable {
val LOG10 = logger()
}
// or alternative for marker interface in companion object of class
class MixedBagOfTricks {
companion object : Loggable {
val LOG11 = logger()
}
}
// or alternative for abstract base class for companion object of class
class MixedBagOfTricks {
companion object: WithLogging() {} // instance 12
fun foo() {
LOG.info("Hello from MixedBagOfTricks")
}
}
// or alternative for abstract base class for our actual class
class MixedBagOfTricks : WithLogging() { // instance 13
fun foo() {
LOG.info("Hello from MixedBagOfTricks")
}
}
All 13 instances of the loggers created in this sample will produce the same logger name, and output:
Dec 26, 2015 11:39:00 AM org.stackoverflow.kotlin.test.MixedBagOfTricks foo
INFO: Hello from MixedBagOfTricks
Note: The unwrapCompanionClass() method ensures that we do not generate a logger named after the companion object but rather the enclosing class. This is the current recommended way to find the class containing the companion object. Stripping "$Companion" from the name using removeSuffix() does not work since companion objects can be given custom names.
Have a look at the kotlin-logging library.
It allows logging like that:
private val logger = KotlinLogging.logger {}
class Foo {
logger.info{"wohoooo $wohoooo"}
}
Or like that:
class FooWithLogging {
companion object: KLogging()
fun bar() {
logger.info{"wohoooo $wohoooo"}
}
}
I also wrote a blog post comparing it to AnkoLogger: Logging in Kotlin & Android: AnkoLogger vs kotlin-logging
Disclaimer: I am the maintainer of that library.
Edit: kotlin-logging now has multiplatform support: https://github.com/MicroUtils/kotlin-logging/wiki/Multiplatform-support
KISS: For Java Teams Migrating to Kotlin
If you don't mind providing the class name on each instantiation of the logger (just like java), you can keep it simple by defining this as a top-level function somewhere in your project:
import org.slf4j.LoggerFactory
inline fun <reified T:Any> logger() = LoggerFactory.getLogger(T::class.java)
This uses a Kotlin reified type parameter.
Now, you can use this as follows:
class SomeClass {
// or within a companion object for one-instance-per-class
val log = logger<SomeClass>()
...
}
This approach is super-simple and close to the java equivalent, but just adds some syntactical sugar.
Next Step: Extensions or Delegates
I personally prefer going one step further and using the extensions or delegates approach. This is nicely summarized in #JaysonMinard's answer, but here is the TL;DR for the "Delegate" approach with the log4j2 API (UPDATE: no need to write this code manually any more, as it has been released as an official module of the log4j2 project, see below). Since log4j2, unlike slf4j, supports logging with Supplier's, I've also added a delegate to make using these methods simpler.
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import org.apache.logging.log4j.util.Supplier
import kotlin.reflect.companionObject
/**
* An adapter to allow cleaner syntax when calling a logger with a Kotlin lambda. Otherwise calling the
* method with a lambda logs the lambda itself, and not its evaluation. We specify the Lambda SAM type as a log4j2 `Supplier`
* to avoid this. Since we are using the log4j2 api here, this does not evaluate the lambda if the level
* is not enabled.
*/
class FunctionalLogger(val log: Logger): Logger by log {
inline fun debug(crossinline supplier: () -> String) {
log.debug(Supplier { supplier.invoke() })
}
inline fun debug(t: Throwable, crossinline supplier: () -> String) {
log.debug(Supplier { supplier.invoke() }, t)
}
inline fun info(crossinline supplier: () -> String) {
log.info(Supplier { supplier.invoke() })
}
inline fun info(t: Throwable, crossinline supplier: () -> String) {
log.info(Supplier { supplier.invoke() }, t)
}
inline fun warn(crossinline supplier: () -> String) {
log.warn(Supplier { supplier.invoke() })
}
inline fun warn(t: Throwable, crossinline supplier: () -> String) {
log.warn(Supplier { supplier.invoke() }, t)
}
inline fun error(crossinline supplier: () -> String) {
log.error(Supplier { supplier.invoke() })
}
inline fun error(t: Throwable, crossinline supplier: () -> String) {
log.error(Supplier { supplier.invoke() }, t)
}
}
/**
* A delegate-based lazy logger instantiation. Use: `val log by logger()`.
*/
#Suppress("unused")
inline fun <reified T : Any> T.logger(): Lazy<FunctionalLogger> =
lazy { FunctionalLogger(LogManager.getLogger(unwrapCompanionClass(T::class.java))) }
// unwrap companion class to enclosing class given a Java Class
fun <T : Any> unwrapCompanionClass(ofClass: Class<T>): Class<*> {
return if (ofClass.enclosingClass != null && ofClass.enclosingClass.kotlin.companionObject?.java == ofClass) {
ofClass.enclosingClass
} else {
ofClass
}
}
Log4j2 Kotlin Logging API
Most of the previous section has been directly adapted to produce the Kotlin Logging API module, which is now an official part of Log4j2 (disclaimer: I am the primary author). You can download this directly from Apache, or via Maven Central.
Usage is basically as describe above, but the module supports both interface-based logger access, a logger extension function on Any for use where this is defined, and a named logger function for use where no this is defined (such as top-level functions).
As a good example of logging implementation I'd like to mention Anko which uses a special interface AnkoLogger which a class that needs logging should implement. Inside the interface there's code that generates a logging tag for the class. Logging is then done via extension functions which can be called inside the interace implementation without prefixes or even logger instance creation.
I don't think this is idiomatic, but it seems a good approach as it requires minimum code, just adding the interface to a class declaration, and you get logging with different tags for different classes.
The code below is basically AnkoLogger, simplified and rewritten for Android-agnostic usage.
First, there's an interface which behaves like a marker interface:
interface MyLogger {
val tag: String get() = javaClass.simpleName
}
It lets its implementation use the extensions functions for MyLogger inside their code just calling them on this. And it also contains logging tag.
Next, there is a general entry point for different logging methods:
private inline fun log(logger: MyLogger,
message: Any?,
throwable: Throwable?,
level: Int,
handler: (String, String) -> Unit,
throwableHandler: (String, String, Throwable) -> Unit
) {
val tag = logger.tag
if (isLoggingEnabled(tag, level)) {
val messageString = message?.toString() ?: "null"
if (throwable != null)
throwableHandler(tag, messageString, throwable)
else
handler(tag, messageString)
}
}
It will be called by logging methods. It gets a tag from MyLogger implementation, checks logging settings and then calls one of two handlers, the one with Throwable argument and the one without.
Then you can define as many logging methods as you like, in this way:
fun MyLogger.info(message: Any?, throwable: Throwable? = null) =
log(this, message, throwable, LoggingLevels.INFO,
{ tag, message -> println("INFO: $tag # $message") },
{ tag, message, thr ->
println("INFO: $tag # $message # $throwable");
thr.printStackTrace()
})
These are defined once for both logging just a message and logging a Throwable as well, this is done with optional throwable parameter.
The functions that are passed as handler and throwableHandler can be different for different logging methods, for example, they can write the log to file or upload it somewhere. isLoggingEnabled and LoggingLevels are omitted for brevity, but using them provides even more flexibility.
It allows for the following usage:
class MyClass : MyLogger {
fun myFun() {
info("Info message")
}
}
There is a small drawback: a logger object will be needed for logging in package-level functions:
private object MyPackageLog : MyLogger
fun myFun() {
MyPackageLog.info("Info message")
}
Would something like this work for you?
class LoggerDelegate {
private var logger: Logger? = null
operator fun getValue(thisRef: Any?, property: KProperty<*>): Logger {
if (logger == null) logger = Logger.getLogger(thisRef!!.javaClass.name)
return logger!!
}
}
fun logger() = LoggerDelegate()
class Foo { // (by the way, everything in Kotlin is public by default)
companion object { val logger by logger() }
}
Anko
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")
}
}
kotlin-logging
kotlin-logging(Github project - kotlin-logging ) library allows you to write logging code like below:
class FooWithLogging {
companion object: KLogging()
fun bar() {
logger.info{"Item $item"}
}
}
StaticLog
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")
timberkt
If you'd already used Jake Wharton's Timber logging library check timberkt.
This library builds on Timber with an API that's easier to use from Kotlin. Instead of using formatting parameters, you pass a lambda that is only evaluated if the message is logged.
Code example:
// Standard timber
Timber.d("%d %s", intVar + 3, stringFun())
// Kotlin extensions
Timber.d { "${intVar + 3} ${stringFun()}" }
// or
d { "${intVar + 3} ${stringFun()}" }
Check also: Logging in Kotlin & Android: AnkoLogger vs kotlin-logging
Hope it will help
That's what companion objects are for, in general: replacing static stuff.
What about an extension function on Class instead? That way you end up with:
public fun KClass.logger(): Logger = LoggerFactory.getLogger(this.java)
class SomeClass {
val LOG = SomeClass::class.logger()
}
Note - I've not tested this at all, so it might not be quite right.
First, you can add extension functions for logger creation.
inline fun <reified T : Any> getLogger() = LoggerFactory.getLogger(T::class.java)
fun <T : Any> T.getLogger() = LoggerFactory.getLogger(javaClass)
Then you will be able to create a logger using the following code.
private val logger1 = getLogger<SomeClass>()
private val logger2 = getLogger()
Second, you can define an interface that provides a logger and its mixin implementation.
interface LoggerAware {
val logger: Logger
}
class LoggerAwareMixin(containerClass: Class<*>) : LoggerAware {
override val logger: Logger = LoggerFactory.getLogger(containerClass)
}
inline fun <reified T : Any> loggerAware() = LoggerAwareMixin(T::class.java)
This interface can be used in the following way.
class SomeClass : LoggerAware by loggerAware<SomeClass>() {
// Now you can use a logger here.
}
create companion object and mark the appropriate fields with #JvmStatic annotation
There are many great answers here already, but all of them concern adding a logger to a class, but how would you do that to do logging in Top Level Functions?
This approach is generic and simple enough to work well in both classes, companion objects and Top Level Functions:
package nieldw.test
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import org.junit.jupiter.api.Test
fun logger(lambda: () -> Unit): Lazy<Logger> = lazy { LogManager.getLogger(getClassName(lambda.javaClass)) }
private fun <T : Any> getClassName(clazz: Class<T>): String = clazz.name.replace(Regex("""\$.*$"""), "")
val topLog by logger { }
class TopLevelLoggingTest {
val classLog by logger { }
#Test
fun `What is the javaClass?`() {
topLog.info("THIS IS IT")
classLog.info("THIS IS IT")
}
}
I have heard of no idiom in this regard.
The simpler the better, so I would use a top-level property
val logger = Logger.getLogger("package_name")
This practice serves well in Python, and as different as Kotlin and Python might appear, I believe they are quite similar in their "spirit" (speaking of idioms).
Slf4j example, same for others. This even works for creating package level logger
/**
* Get logger by current class name.
*/
fun getLogger(c: () -> Unit): Logger =
LoggerFactory.getLogger(c.javaClass.enclosingClass)
Usage:
val logger = getLogger { }
fun <R : Any> R.logger(): Lazy<Logger> = lazy {
LoggerFactory.getLogger((if (javaClass.kotlin.isCompanion) javaClass.enclosingClass else javaClass).name)
}
class Foo {
val logger by logger()
}
class Foo {
companion object {
val logger by logger()
}
}
This is still WIP (almost finished) so I'd like to share it:
https://github.com/leandronunes85/log-format-enforcer#kotlin-soon-to-come-in-version-14
The main goal of this library is to enforce a certain log style across a project. By having it generate Kotlin code I'm trying to address some of the issues mentioned in this question. With regards to the original question what I usually tend to do is to simply:
private val LOG = LogFormatEnforcer.loggerFor<Foo>()
class Foo {
}
You can simply build your own "library" of utilities. You don't need a large library for this task which will make your project heavier and complex.
For instance, you can use Kotlin Reflection to get the name, type and value of any class property.
First of all, make sure you have the meta-dependency settled in your build.gradle:
dependencies {
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
}
Afterwards, you can simply copy and paste this code into your project:
import kotlin.reflect.full.declaredMemberProperties
class LogUtil {
companion object {
/**
* Receives an [instance] of a class.
* #return the name and value of any member property.
*/
fun classToString(instance: Any): String {
val sb = StringBuilder()
val clazz = instance.javaClass.kotlin
clazz.declaredMemberProperties.forEach {
sb.append("${it.name}: (${it.returnType}) ${it.get(instance)}, ")
}
return marshalObj(sb)
}
private fun marshalObj(sb: StringBuilder): String {
sb.insert(0, "{ ")
sb.setLength(sb.length - 2)
sb.append(" }")
return sb.toString()
}
}
}
Example of usage:
data class Actor(val id: Int, val name: String) {
override fun toString(): String {
return classToString(this)
}
}
For Kotlin Multiplaform logging I could not find a library that had all the features I needed so I ended up writing one. Please check out KmLogging. The features it implements is:
Uses platform specific logging on each platform: Log on Android, os_log on iOS, and console on JavaScript.
High performance. Only 1 boolean check when disabled. I like to put in lots of logging and want all of it turned off when release and do not want to pay much overhead for having lots of logging. Also, when logging is on it needs to be really performant.
Extensible. Need to be able add other loggers such as logging to Crashlytics, etc.
Each logger can log at a different level. For example, you may only want info and above going to Crashlytics and all other loggers disabled in production.
To use:
val log = logging()
log.i { "some message" }