Log4j – Logging in Files

In this article, you will see how to write your logging information into a file.

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml


1. Properties file

The following configuration writes your log information in logging.txt file.


log4j.rootLogger=INFO, FILE
log4j.appender.FILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n 

2. Log4j in Java Program

The following Java class is a very simple example that initializes, and then uses, the Log4J logging library for Java applications.

package com.kruders;

import org.apache.log4j.Logger;

public class HelloWorld {
	static final Logger logger = Logger.getLogger(HelloWorld.class);
	public static void main(String[] args) {
		logger.info("Hello World!!!");

When you run the above example , following screen will be displayed as shown in Figure 1.1

Figure 1.1 Figure 1.1

You can download the source code of this example here.


No comments yet.

Leave a Reply