天天看點

Cloudopt-logger — Kotlin 實作的日志架構擴充

Cloudopt-logger 是一個基于 Kotlin 開發的可擴充、可配置的日志架構擴充,支援 Java、Kotlin 及 Android。

Cloudopt-logger — Kotlin 實作的日志架構擴充
Cloudopt-logger — Kotlin 實作的日志架構擴充
具有以下特性:

  • 支援彩色的日志輸出。
  • 支援多種日志架構,如Slf4j、Log4j等等。
  • 易于擴充。
  • 更人性化和友善調試的輸出。
中文文檔

安裝

在Maven中引入:

<dependency>
    <groupId>net.cloudopt.logger</groupId>
    <artifactId>cloudopt-logger</artifactId>
    <version>1.0.1</version>
</dependency>           

如果您是使用Slf4j的話,需要引入相應的庫,如:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>           

如何使用

使用起來非常簡單,隻需要引入Logger類即可,下面是幾個示例:

package net.cloudopt.logger
import org.junit.Test

class TestCase {

    private val logger = Logger.getLogger(TestCase::class.java)

    @Test
    fun example1() {
        logger.debug("Start init....")
        logger.info("Operation successful!")
        logger.warn("The value must be not nul.")
        logger.error("Unable to acquire lock!")
    }

    @Test
    fun example2() {
        logger.info("Please Wait.... ${Colorer.blue("100")}")
        logger.info("Please Wait.... ${Colorer.yellow("200")}")
        logger.info("Please Wait.... ${Colorer.red("300")}")
    }

    @Test
    fun example3() {
        val configuration = LoggerConfiguration()
        configuration.run {
            this.color = false
        }
        Logger.configuration = configuration
        example1()
    }

    @Test
    fun example4() {
        val configuration = LoggerConfiguration()
        configuration.run {
            this.debugPrefix = "DEBUG"
            this.infoPrefix = "INFO"
            this.warnPrefix = "WARN"
            this.errorPrefix = "ERROR"
        }
        Logger.configuration = configuration
        example1()
    }
}           

如果您想要修改任何輸出的字元的顔色,隻需要通過Colorer.xxx的方法包裹即可。目前已經内置了八種顔色。

如何擴充

目前已經内置了對Slf4j的支援,通過Slf4j可以支援logback、log4j、log4j2等等,如果您需要直接支援或者支援其他日志架構,您可以參考Slf4jLoggerProvider,自行實作。

本文來自雲栖社群合作夥伴“開源中國”

本文作者:h4cd

原文連結

繼續閱讀