关于kotlin:关于Kotlin中日志的使用方法

7次阅读

共计 2038 个字符,预计需要花费 6 分钟才能阅读完成。

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,这样能力传递给前面的getLoggerT::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.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 参考

  • Github
  • 码云
  • CODE.CHINA

6 参考

1、kotlin-logging

2、Kotlin 官网 - 内联函数

正文完
 0