Kotlin - 2. Kotlin中日志的使用方法

1 引言

想必学过Java的人都知道一个@Slf4j使用得多么的舒服:

1 @Slf4j
2 public class TestController{
3     @GetMapping("/test")
4     public String test(){
5         log.debug("debug");     
6         return "test";
7     }
8 }

 

但是很不幸在Kotlin中并没有这种注解,因此,本文给出了一种类似@Slf4j注解在Kotlin中的使用方法,以及介绍一个100%使用Kotlin编写的日志库。

2 动手写@Slf4j

很简单,先上代码:

 1 import org.slf4j.Logger
 2 import org.slf4j.LoggerFactory
 3 
 4 @Target(AnnotationTarget.CLASS)
 5 @Retention(AnnotationRetention.RUNTIME)
 6 annotation class Slf4j{
 7     companion object{
 8         val <reified T> T.log: Logger
 9         inline get() = LoggerFactory.getLogger(T::class.java)
10     }
11 }

 

逐行解释如下:

  • @Target:与Java中的@Target类似,注解的目标,这里是类
  • @Retention:与Java中的@Retention类似,运行时保留
  • annotation class:声明一个注解
  • companion object:伴生对象
  • val <reified T> T.log:Logger:声明一个Logger类型的泛型对象
  • inline get() = LoggerFactory.getLogger(T::class.java):声明getter为内联,声明为内联才能使用T,这样才能传递给后面的getLoggerT::class.java相当于Java中的T.class,也就是getLogger(T::class.java)相当于getLogger(SomeClass.class)

使用很简单:

1 @RestController
2 @Slf4j
3 class TestController {
4     @GetMapping("/test")
5     fun test():String{
6         log.warn("cc")
7         return "test"
8     }
9 }

 

直接类上加一个注解,就可以使用log.info/log.warn之类的方法了。

3 kotlin-logging

上面介绍了注解的使用方法,如果不想使用注解的话,可以使用别人的库,比如kotlin-logging

kotlin-logging是一个100%使用Kotlin编写的轻度封装了slf4j的开源日志库,已经收获1.4kstar

 
在这里插入图片描述

依赖如下:

<dependency>
    <groupId>io.github.microutils</groupId>
    <artifactId>kotlin-logging-jvm</artifactId>
    <version>2.0.6</version>
</dependency>

 

Gradle

implementation 'io.github.microutils:kotlin-logging-jvm:2.0.6'

 

引入时,只需要在对应的类中创建一个属性即可:

private val logger = KotlinLogging.logger {}

 

使用时,直接调用其中的info/debug/error等即可:

import mu.KotlinLogging
private val logger = KotlinLogging.logger {} 
class FooWithLogging {
    val message = "world"
    fun bar() {
        logger.debug { "hello $message" }
    }
}

 

4 两者结合使用

当然,也可以将注解与kotlin-logging结合一下使用,首先,笔者简单地看了一下KotlinLogging的接口:

 
在这里插入图片描述

提供了三个对外的logger方法,参数分别是:

  • 函数
  • 字符串
  • org.slf4j.Logger

对外没有提供类似getLogger(Class<?> clazz)这样的用类作为参数的方法,因此,需要通过泛型获取到具体类的名字并使用第二种方法构造mu.KLogger

import mu.KotlinLogging
import org.slf4j.Logger

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Slf4j{
    companion object{
        val <reified T> T.log: Logger
        inline get() = KotlinLogging.logger{T::class.java.name}
    }
}

 

使用方法同上,直接加一个@Slf4j即可使用。

5 完整Demo参考

6 参考

1、kotlin-logging

2、Kotlin官网-内联函数

 

posted @ 2021-12-07 15:47  大大章鱼  阅读(197)  评论(0编辑  收藏  举报