基于scala-logging
和logback
的日志打印模板,其中logback
是一个更高效/更优于log4j
的日志打印框架,目前正逐渐替代log4j
的位置,以下为实现日志打印的几个步骤:
1. 添加依赖
以maven
为例:
<dependency>
<groupId>com.typesafe.scala-logging</groupId>
<artifactId>scala-logging_${scala.version}</artifactId>
<version>3.5.0</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. 代码操作
import com.typesafe.scalalogging.Logger
private[this] val logger = Logger(this.getClass)
logger.info("server ready ...... ")
打印效果:
23:16:05.668 TKD [main] INFO c.z.p.monitorcenter.CEApplication$ - server ready ......
23:16:05.676 TKD [main] INFO c.z.p.monitorcenter.CEApplication$ - RabbitMq Consumer Thread Start ......