1. 程式人生 > >Scala日誌列印

Scala日誌列印

基於scala-logging和logback的日誌列印模板,其中logback是一個更高效/更優於log4j的日誌列印框架,目前正逐漸替代log4j的位置,以下為實現日誌列印的幾個步驟:

1. 新增依賴

以maven為例:

<dependency>
   <groupId>com.typesafe.scala-logging</groupId>
    <artifactId>scala-logging_2.11</artifactId>
    <version>3.7.2</version>
</dependency>
<dependency>
   <groupId>ch.qos.logback</groupId>
   <artifactId>logback-classic</artifactId>
   <version>1.2.3</version>
</dependency>

2. 新增配置檔案

在resources目錄下新增logback.xml檔案,該檔案就類似於log4j.properties

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} TKD [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>/tmp/test.log</file>
        <append>true</append>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} TKD [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE"/>
    </root>
    <logger name="scala.slick" level="INFO" />
</configuration>

具體配置自行修改

3. 程式碼操作

object LogTest {
  def main(args: Array[String]): Unit = {
     val logger = Logger(this.getClass)
    logger.info("hello scala")
  }
}