1. Log4j2 Project setup

We setup the project structure as below in Eclipse.

You need to add log4j-api-<version>.jar and log4j-core-<version>.jar libraries to your project. Configuration for log4j2 is in the log4j2.xml file. You can configure to output log messages the the Console, log files, or both. You can change the log level in the configuration file e.g. from INFO to DEBUG to see the debug messages included in the output.

2. Log4j2 Output to Console

<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="log4j2.xsd">
  <Appenders>
    <Console name="Console">
      <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %C:%L [%M] - %m%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Root level="INFO">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

3. Log4j2 Log into File

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
	<Appenders>
		<File name="File" fileName="logs/Log4JTutorial-${date:yyyy-MM-dd_HHmmss-SSS}.log">
			<PatternLayout>
				<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %C:%L [%M] - %m%n
				</Pattern>
			</PatternLayout>
		</File>
	</Appenders>
	<Loggers>
		<Root level="INFO">
			<AppenderRef ref="File" />
		</Root>
	</Loggers>
</Configuration>

4. Log4j2 Both Console and File

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
	<Appenders>
		<Console name="Console">
			<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %C:%L [%M] - %m%n" />
		</Console>
		<File name="File" fileName="logs/Log4JTutorial-${date:yyyy-MM-dd_HHmmss-SSS}.log">
			<PatternLayout>
				<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %C:%L [%M] - %m%n
				</Pattern>
			</PatternLayout>
		</File>
	</Appenders>
	<Loggers>
		<Root level="INFO">
			<AppenderRef ref="Console" />
			<AppenderRef ref="File" />
		</Root>
	</Loggers>
</Configuration>

5. Log4j2 Rolling File Appender

The log4j2.xml file below is used to create maximum 5 backup log files. Each backup log file as the size of 1 MB. The logfile.log file has the maximum size of 1 MB.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
	<Appenders>
		<RollingFile name="RollingFile">
			<FileName>logs/logfile.log</FileName>
			<FilePattern>logs/logfile-%i.log</FilePattern>
			<PatternLayout>
				<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %C:%L [%M] - %m%n
				</Pattern>
			</PatternLayout>
			<Policies>
				<SizeBasedTriggeringPolicy size="1 MB" />
			</Policies>
			<DefaultRolloverStrategy max="5" />
		</RollingFile>
	</Appenders>
	<Loggers>
		<Root level="INFO">
			<AppenderRef ref="RollingFile" />
		</Root>
	</Loggers>
</Configuration>

6. Reference