1<?xml version="1.0" encoding="UTF-8"?>
2<Configuration status="WARN" monitorInterval="30">
3 <Properties>
4 <Property name="LOG_PATTERN">
5 %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
6 </Property>
7 </Properties>
8 <Appenders>
9 <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
10 <PatternLayout pattern="${LOG_PATTERN}"/>
11 </Console>
12 </Appenders>
13 <Loggers>
14 <Logger name="com.example.log4j2demo" level="debug" additivity="false">
15 <AppenderRef ref="ConsoleAppender" />
16 </Logger>
17
18 <Root level="info">
19 <AppenderRef ref="ConsoleAppender" />
20 </Root>
21 </Loggers>
22</Configuration>
23
1package com.example.log4j2demo;
2
3import org.apache.logging.log4j.LogManager;
4import org.apache.logging.log4j.Logger;
5import org.springframework.boot.ApplicationArguments;
6import org.springframework.boot.ApplicationRunner;
7import org.springframework.boot.SpringApplication;
8import org.springframework.boot.autoconfigure.SpringBootApplication;
9
10@SpringBootApplication
11public class Log4j2DemoApplication implements ApplicationRunner {
12 private static final Logger logger = LogManager.getLogger(Log4j2DemoApplication.class);
13
14 public static void main(String[] args) {
15 SpringApplication.run(Log4j2DemoApplication.class, args);
16 }
17
18 @Override
19 public void run(ApplicationArguments applicationArguments) throws Exception {
20 logger.debug("Debugging log");
21 logger.info("Info log");
22 logger.warn("Hey, This is a warning!");
23 logger.error("Oops! We have an Error. OK");
24 logger.fatal("Damn! Fatal error. Please fix me.");
25 }
26}
27
1<!-- Exclude Spring Boot's Default Logging -->
2<dependency>
3 <groupId>org.springframework.boot</groupId>
4 <artifactId>spring-boot-starter</artifactId>
5 <exclusions>
6 <exclusion>
7 <groupId>org.springframework.boot</groupId>
8 <artifactId>spring-boot-starter-logging</artifactId>
9 </exclusion>
10 </exclusions>
11</dependency>
12
13<!-- Add Log4j2 Dependency -->
14<dependency>
15 <groupId>org.springframework.boot</groupId>
16 <artifactId>spring-boot-starter-log4j2</artifactId>
17</dependency>
18
1<!-- Rolling File Appender -->
2<RollingFile name="FileAppender" fileName="logs/log4j2-demo.log"
3 filePattern="logs/log4j2-demo-%d{yyyy-MM-dd}-%i.log">
4 <PatternLayout>
5 <Pattern>${LOG_PATTERN}</Pattern>
6 </PatternLayout>
7 <Policies>
8 <SizeBasedTriggeringPolicy size="10MB" />
9 </Policies>
10 <DefaultRolloverStrategy max="10"/>
11</RollingFile>
12