Last active
April 25, 2020 05:32
-
-
Save ABashkirova/da50b8997933e9df7b984b5e85bda864 to your computer and use it in GitHub Desktop.
InjectLogger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package di.logger | |
import kotlin.annotation.AnnotationRetention.RUNTIME | |
import kotlin.annotation.AnnotationTarget.* | |
@Target(FIELD) | |
@Retention(RUNTIME) | |
annotation class InjectLogger |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.inject.MembersInjector | |
import org.apache.logging.log4j.kotlin.KotlinLogger | |
import org.apache.logging.log4j.kotlin.logger | |
import java.lang.reflect.Field | |
internal class Log4JMembersInjector<T>(private val field: Field) : MembersInjector<T> { | |
private val logger: KotlinLogger by lazy { logger(field.declaringClass.name) } | |
init { | |
field.isAccessible = true | |
} | |
@Throws(RuntimeException::class) | |
override fun injectMembers(t: T) { | |
try { | |
field.set(t, logger) | |
} catch (e: IllegalAccessException) { | |
throw RuntimeException(e) | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.inject.TypeLiteral | |
import com.google.inject.spi.TypeEncounter | |
import com.google.inject.spi.TypeListener | |
import org.apache.logging.log4j.kotlin.KotlinLogger | |
internal class Log4JTypeListener : TypeListener { | |
override fun <T> hear(typeLiteral: TypeLiteral<T>, typeEncounter: TypeEncounter<T>) { | |
var clazz = typeLiteral.rawType | |
while (clazz != null) { | |
clazz.declaredFields | |
.asSequence() | |
.filter { it.type === KotlinLogger::class.java && it.isAnnotationPresent(InjectLogger::class.java) } | |
.forEach { typeEncounter.register(Log4JMembersInjector(it)) } | |
clazz = clazz.superclass | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment