Kotlin中日志的使用方法详解

1 引言

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

@Slf4j
public class TestController{
 @GetMapping("/test")
 public String test(){
  log.debug("debug");  
  return "test";
 }
}

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

2 动手写@Slf4j

很简单,先上代码:

import org.slf4j.Logger
import org.slf4j.LoggerFactory

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

逐行解释如下:

  • @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,这样才能传递给后面的getLogger,T::class.java相当于Java中的T.class,也就是getLogger(T::class.java)相当于getLogger(SomeClass.class)

使用很简单:

@RestController
@Slf4j
class TestController {
  @GetMapping("/test")
  fun test():String{
    log.warn("cc")
    return "test"
  }
}

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

3 kotlin-logging

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

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

Kotlin中日志的使用方法详解

依赖如下:

<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的接口:

Kotlin中日志的使用方法详解

提供了三个对外的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官网-内联函数