Java - Logging using Log4j
by
Jeremy Canfield |
Updated: February 23 2023
| Java articles
There are various ways to go about append events to a custom log file in Java.
- Using BufferedOutputStream and FileOutputStream
- Using Log4j (this article)
- Using java.util.logging
Download the latest log4j-core-<version>.jar and log4j-api-<version>.jar files from https://mvnrepository.com and add the JARs to your Java Build Path.
Create the Log4j.xml file in your project (e.g. WEB-INF/lib/Log4j.xml) and add the following to the Log4j.xml file. In this example, events at log level INFO will be displayed on the console and appended to the app.log file.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<Configuration>
<Appenders>
<Console name="LogToConsole" target="SYSTEM_OUT">
<PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</Console>
<File name="LogToFile" fileName="app.log">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Logger name="default" level="info"/>
<Root level="trace">
<AppenderRef ref="LogToFile"/>
<AppenderRef ref="LogToConsole"/>
</Root>
</Loggers>
</Configuration>
Here is an example of how you could log events using Log4j.
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
public class Main {
private static final Logger logger = LogManager.getLogger(Main.class);
public String hello() {
String greeting = "Hello World";
logger.info(greeting);
return greeting;
}
}
Did you find this article helpful?
If so, consider buying me a coffee over at