We've seen how to create a profile earlier. This tutorial will explain how to generate debug information and log in a simple text file.
Here is a simple configuration file created in our example. Repeat here:
- Download the latest log4j library: http://logging.apache.org/log4j/2.x/download.html
The root logger level is defined as debug and the connection Appender is named file.
The Appender file is defined as Org.apache.log4j.FileAppender and is written to a log directory named "Log.out".
The layout pattern defined is%m%n, which means that a line break is automatically added after the log message is printed.
So the contents of the Log4j.properties file are as follows:
=/usr/home/= DEBUG, file# Define the FILE appenderlog4j.appender.FILE= Org.apache.log4j.FileAppenderlog4j.appender.FILE.File=${log}/ for FILE Appenderlog4j.appender.FILE.layout= Org.apache.log4j.PatternLayoutlog4j.appender.FILE.layout.conversionPattern=%m%n
To use log4j in a Java program:
The following Java class is a very simple example of a Java application initializing and then using the log4j Log library.
ImportOrg.apache.log4j.Logger;ImportJava.io.*;Importjava.sql.SQLException;ImportJava.util.*; Public classlog4jexample{/*Get Actual class name to being printed on*/ StaticLogger log =Logger.getlogger (log4jexample.class. GetName ()); Public Static voidMain (string[] args)throwsioexception,sqlexception{Log.debug ("Hello This is a debug message"); Log.info ("Hello This is an info message"); }}
Compile and run:
Here are the steps to compile and run the above program. Be sure to set the path and classpath appropriately before compiling and executing.
All libraries should be available in the CLASSPATH and log4j.properties files in path. So, do the following:
Create the log4j.properties as shown in.
Create the Log4jexample.java as shown, and compile it.
Executes the log4jexample binary run program.
The/usr/home/log4j/log.out file in the inside will get the following result:
this was an info message
log4j Tutorial 5, sample programs