Spring Boot Logging1

Log library

In Spring Boot, logback is default logging.
The default dependencies are following

  • logback-classic
  • logback-core
  • log4j
  • slf4j

Setting file(logback.xml)

The directory is src/main/resources/logback.xml

Sub file

We can use sub xml file.

<configuration>
  <include resource="dev.xml"/>
</configuration>

sub file(dev.xml)

<included>
</included>

Simple Appender and Code

Appender setting

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
  <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
     <param name="Pattern" value="%d{HH:mm:ss.SSS} &#91;%thread&#93; %-5level %logger - %msg%n" />
  </encoder>
</appender>

<root level="{log.level.root:-INFO}">
  <appender-ref ref="STDOUT"/>
</root>	

Code

Logger logger = LoggerFactory.getLogger(BasicTestController.class);
logger.info("Method1");

Result

18:41:27.610 [http-nio-8080-exec-1] INFO  VISITLOG - Welcome - HttpSample

File and Log rotate

Sometimes, we would like to keep special logs for several reasons.
Log is piled a lot of data and file size becomes so big.
Before the file becomes much, separate(change file name per day) and compress data(.zip, .gz)
This is log rotate.
To realize this, we can use fileNamePattern

Setting

<appender name="VISITLOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
   <file>D:\logs\visit.log</file>
   <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
   <fileNamePattern>D:\logs\visit.log.%d{yyyy-MM-dd}.zip</fileNamePattern>
      <maxHistory>${log.max_date:-7}</maxHistory>
   </rollingPolicy>
   <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
	<param name="Pattern" value="%msg%n" />
   </encoder>
</appender>

<logger name="VISITLOG">
   <level value="INFO" />
   <appender-ref ref="VISITLOG" />
</logger>

Codes

Logger visitlogger = LoggerFactory.getLogger("VISITLOG");
visitlogger.info("Welcome - HttpSample");

Result d:\logs\visit.log

Welcome - HttpSample