User-Profile-Image
hankin
  • 5
  • Java
  • Kotlin
  • Spring
  • Web
  • SQL
  • MegaData
  • More
  • Experience
  • Enamiĝu al vi
  • 分类
    • Zuul
    • Zookeeper
    • XML
    • WebSocket
    • Web Notes
    • Web
    • Vue
    • Thymeleaf
    • SQL Server
    • SQL Notes
    • SQL
    • SpringSecurity
    • SpringMVC
    • SpringJPA
    • SpringCloud
    • SpringBoot
    • Spring Notes
    • Spring
    • Servlet
    • Ribbon
    • Redis
    • RabbitMQ
    • Python
    • PostgreSQL
    • OAuth2
    • NOSQL
    • Netty
    • MySQL
    • MyBatis
    • More
    • MinIO
    • MegaData
    • Maven
    • LoadBalancer
    • Kotlin Notes
    • Kotlin
    • Kafka
    • jQuery
    • JavaScript
    • Java Notes
    • Java
    • Hystrix
    • Git
    • Gateway
    • Freemarker
    • Feign
    • Eureka
    • ElasticSearch
    • Docker
    • Consul
    • Ajax
    • ActiveMQ
  • 页面
    • 归档
    • 摘要
    • 杂图
    • 问题随笔
  • 友链
    • Spring Cloud Alibaba
    • Spring Cloud Alibaba - 指南
    • Spring Cloud
    • Nacos
    • Docker
    • ElasticSearch
    • Kotlin中文版
    • Kotlin易百
    • KotlinWeb3
    • KotlinNhooo
    • 前端开源搜索
    • Ktorm ORM
    • Ktorm-KSP
    • Ebean ORM
    • Maven
    • 江南一点雨
    • 江南国际站
    • 设计模式
    • 熊猫大佬
    • java学习
    • kotlin函数查询
    • Istio 服务网格
    • istio
    • Ktor 异步 Web 框架
    • PostGis
    • kuangstudy
    • 源码地图
    • it教程吧
    • Arthas-JVM调优
    • Electron
    • bugstack虫洞栈
    • github大佬宝典
    • Sa-Token
    • 前端技术胖
    • bennyhuo-Kt大佬
    • Rickiyang博客
    • 李大辉大佬博客
    • KOIN
    • SQLDelight
    • Exposed-Kt-ORM
    • Javalin—Web 框架
    • http4k—HTTP包
    • 爱威尔大佬
    • 小土豆
    • 小胖哥安全框架
    • 负雪明烛刷题
    • Kotlin-FP-Arrow
    • Lua参考手册
    • 美团文章
    • Java 全栈知识体系
    • 尼恩架构师学习
    • 现代 JavaScript 教程
    • GO相关文档
    • Go学习导航
    • GoCN社区
    • GO极客兔兔-案例
    • 讯飞星火GPT
    • Hollis博客
    • PostgreSQL德哥
    • 优质博客推荐
    • 半兽人大佬
    • 系列教程
    • PostgreSQL文章
    • 云原生资料库
    • 并发博客大佬
Help?

Please contact us on our email for need any support

Support
    首页   ›   Kotlin   ›   Kotlin Notes   ›   正文
Kotlin Notes

Kotlin—日志的使用方法

2021-06-30 17:15:51
1663  0 0
参考目录 隐藏
1) 1、手写 @slf4j
2) 2、 kotlin-logging
3) 3、结合注解

阅读完需:约 3 分钟

都知道java中的@Slf4j使用得多么的舒服:

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

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

1、手写 @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)
    }
}

这里用的是java中的slf4j日志类,来完成。

逐行解释如下:

  • @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之类的方法了。

2、 kotlin-logging

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

kotlin-logging是一个100%使用Kotlin编写的轻度封装了slf4j的开源日志库。

MicroUtils/kotlin-logging: Lightweight logging framework for Kotlin. A convenient and performant logging library wrapping slf4j with Kotlin extensions (github.com)

依赖如下:

        <dependency>
            <groupId>io.github.microutils</groupId>
            <artifactId>kotlin-logging-jvm</artifactId>
            <version>2.0.8</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" }
    }
}

3、结合注解

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

public object KotlinLogging {
    public final fun logger(func: () -> kotlin.Unit): mu.KLogger { /* compiled code */ }

    public final fun logger(name: kotlin.String): mu.KLogger { /* compiled code */ }

    public final fun logger(underlyingLogger: org.slf4j.Logger): mu.KLogger { /* compiled code */ }
}

提供了三个对外的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即可使用。

如本文“对您有用”,欢迎随意打赏作者,让我们坚持创作!

0 打赏
Enamiĝu al vi
不要为明天忧虑.因为明天自有明天的忧虑.一天的难处一天当就够了。
543文章 68评论 297点赞 609054浏览

随机文章
Spring—JdbcTemplate模板类的使用(补充)
5年前
SpringSecurity—多种加密方案共存
4年前
JAVA对json操作—Jackson,Gson,fastjson
5年前
SpringBoot—logback日志配置
5年前
HttpServletRequest常用的方法
5年前
博客统计
  • 日志总数:543 篇
  • 评论数目:68 条
  • 建站日期:2020-03-06
  • 运行天数:1949 天
  • 标签总数:23 个
  • 最后更新:2024-12-20
Copyright © 2025 网站备案号: 浙ICP备20017730号 身体没有灵魂是死的,信心没有行为也是死的。
主页
页面
  • 归档
  • 摘要
  • 杂图
  • 问题随笔
博主
Enamiĝu al vi
Enamiĝu al vi 管理员
To be, or not to be
543 文章 68 评论 609054 浏览
测试
测试
看板娘
赞赏作者

请通过微信、支付宝 APP 扫一扫

感谢您对作者的支持!

 支付宝 微信支付