Home » Enterprise Java » Log4j » Log4j Specific File Location Example

About Rajagopal ParthaSarathi

Rajagopal works in software industry solving enterprise-scale problems for customers across geographies specializing in open source distributed platforms. He currently holds masters in computer science with focus on cloud computing from Illinois Institute of Technology. His current interests include but not limited to machine learning and big data engineering.

Log4j Specific File Location Example

This article is a tutorial about logging to files in specific location. We will first checkout other logging methods and then proceed to log to a specific location.

1. Introduction

Log4J(Java) is the widely used logging framework for Java. It continues to grow continuously with recent upgrade of Log4j2. Log4j helps to log files to a file or console or even to a database. Log4j has three basic components to support logging – Logger, Appender and Layouts.

Logger carries out the logging activity and is the interaction point for the application. It is used to specify logging mode, name for the logger and delivers  logs to logging destination with the help of appender. Log4j supports multiple predefined appenders and supports creating custom appenders. Appender does the heavylifting in log4j connecting the logger to destination with the mode specified.

Layout specifies the display format of the logs. Commonly used Layout for Log4j is PatternLayout. A sample pattern is  %d [%t] %-5p (%F: %L) – %m%n. The format strings  for the pattern are as follows:

  • Date –  Full date till micro seconds
  • Thread – JVM thread logging the output
  • Logging Mode – INFO/ERROR/DEBUG/WARN
  • Class – Java Class logging the output
  • Line number – Line number in java class
  • Message – The message logged
  • Default line separator -/n unless specified otherwise

2. Console Logging

We will see first an example of logging to console. This is much similar to using  System.out.println. The differentiator is the ability of Log4j to support logging mode and suppress log messages below the specified threshold.

log4j.rootLogger=INFO, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=INFO
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n
  • Logs are appended to console as specified in line 4
  • Conversion Pattern specifies the display format of the logs

3. File Logging

Console logs do not survive application restarts. In Production grade applications, log files need to be preserved for future analysis. This is achieved by using a file logger which is similar to console logger but it just logs to a specific file rather than console. Below we will see a simple configuration for logging to a file without location specification.

log4j.rootLogger=INFO, fileLogger
log4j.appender.fileLogger.layout=org.apache.log4j.PatternLayout
log4j.appender.fileLogger.layout.ConversionPattern=%d [%t] %-5p (%F:%L) - %m%n
log4j.appender.fileLogger.File=example.log
log4j.appender.fileLogger=org.apache.log4j.DailyRollingFileAppender
log4j.appender.fileLogger.datePattern='.'yyyy-MM-dd-HH-mm

The above configuration represents a DailyRollingFileAppender. This logs the output to a specific file example.log. File is created under the application’s running directory. Appender rotates the log file on daily basis. Application directories are cleared during consecutive deploy. Hence it does not alleviate the concerns of the previous approach.

4. File Logging To Location

Recommended approach is to log files to a specific location in the deployed environment. This is easily achieved by extending our previous example. We just need to provide the location under the File property.

log4j.rootLogger=INFO, fileLogger
log4j.appender.fileLogger.layout=org.apache.log4j.PatternLayout
log4j.appender.fileLogger.layout.ConversionPattern=%d [%t] %-5p (%F:%L) - %m%n
log4j.appender.fileLogger.File=/opt/logs/example.log
log4j.appender.fileLogger=org.apache.log4j.DailyRollingFileAppender
log4j.appender.fileLogger.datePattern='.'yyyy-MM-dd-HH-mm

The key thing to lookout is the file location has been specified for the File property. This controls the location of the output and ensures log files are backed up for future inspection.

5. Execution Steps

  1. Create a simple Java Project in eclipse
  2. Download log4j jar and include in your project by clicking on Project Properties -> Java Build Path -> Libraries -> Add Jars
  3. Copy the below java code in project
  4. Include a single appender in your project at a time
  5. Stop the running project in eclipse after 5 minutes to see various logs

Java Logger Class

package com.jcg.examples;
package com.jcg.examples;
import org.apache.log4j.Logger;
public class LoggerMain {
	public static final Logger logger = Logger.getLogger(LoggerMain.class);
	public static void main(String[] args) {
		while (true) {
			logger.info("This is a test log");
		}
	}
}

6. Summary

In this tutorial we saw logging to a specific file location in log4j with help of examples.

7. Download the Source Code

Download
You can download the full source code of this example here: Log4j Specific File Location Example

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of