Log4j is a simple and flexible logging framework. Application logging equips the developer with detailed context for application failures. With log4j, it is possible to enable logging at runtime without modifying the application binary. The log4j package is designed so that these statements can remain in shipped code without incurring a heavy performance cost.
The two most common configuration options are in practice i.e. using log4j.xml
configuration or using log4j.properties
configuration.
In this log4j xml configuration tutorial, I am showing the example code for log4j.xml configuration.
Read more: Log4j properties file example
1. Log4j maven dependencies
Create a maven java project and update log4j dependencies.
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
2. log4j.xml file
This is the main configuration file having all runtime configuration used by log4j. This file will have log4j appenders information, log level information and output file names for file appenders.
Create this file and put in application classpath.
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration debug="true" xmlns:log4j='http://jakarta.apache.org/log4j/'> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" /> </layout> </appender> <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="demoApplication.log"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" /> </layout> </appender> <root> <priority value ="debug"></priority> <appender-ref ref="console"></appender> <appender-ref ref="fileAppender"></appender> </root> </log4j:configuration>
3. log4j.xml example
package com.howtodoinjava; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; public class Log4jXmlConfigurationExample { static Logger logger = Logger.getLogger(Log4jXmlConfigurationExample.class); public static void main(String[] args) { //DOMConfigurator is used to configure logger from xml configuration file DOMConfigurator.configure("log4j.xml"); //Log in console in and log file logger.debug("Log4j appender configuration is successful !!"); } }
Output in console and demoApplication.log in project root folder:
[main] DEBUG com.howtodoinjava.Log4jXmlConfigurationExample - Log4j xml configuration is successful !!
Now let’s see some log4j.xml examples to output log messages to specific location.
4. Log4j console appender – Logging to console
Java program to output logs to console using ConsoleAppender.
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration debug="true" xmlns:log4j='http://jakarta.apache.org/log4j/'> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" /> </layout> </appender> <root> <priority value ="debug"></priority> <appender-ref ref="console"></appender> </root> </log4j:configuration>
4. Log4j rolling file appender – Logging to file
Java program to output logs to file using RollingFileAppender.
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration debug="true" xmlns:log4j='http://jakarta.apache.org/log4j/'> <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="demoApplication.log"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" /> </layout> </appender> <root> <priority value ="debug"></priority> <appender-ref ref="fileAppender"></appender> </root> </log4j:configuration>
Let me know if any question on log4j.xml configuration and usage.
Happy Learning !!
MANIKANTA NUKALA
I am using log4j configuration for my project. I want to exclude the warn messages from the log. I find that I need to add LevelRangeFilter in the xml configuration file for this. But, I am getting the following error:
Lokesh Gupta
Tried this LevelRangeFilter example.
Diksha
I want only fresh logs to be generated in my Log file each time when I run any scripts.
Can you help on this what changes needs to be done in .xml file.
Lokesh Gupta
Log4j does not add or filter any statement. You need to handle it in application code.
MANIKANTA NUKALA
Use the following param tag inside your appender tag
false will make the log to override the file. true will make the log to append to the file
Another WebSphere Programmer
This looks correct to me. Also by using:
private static Logger log = Logger.getLogger(ClassName.class);
log.info does work and does write to the log file.
But every time I start WebSphere Server I see in red:
log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Also, Log4j.xml is under WEB-INF and log4j-1.2.16.jar is in the Java Build Path/Libraries.
Can you tell me what is wrong with this setup ?
sridhar
I have given only %m%n in my conversionPattern, but im getting a lot of data. why is that?
bajirao gharage
Hi Sir,
Actually we want to dynamic value from java code to print on every line of log file.
Wasim
Hi,
Thanks for sharing this.
How can I log all console output to a file ?
Console output like all the system output i.e system.out.print,system.err.print and all jvm related error/exceptions.
Could you please help me here.
Thanks,
Wasim
Lokesh Gupta
After you run above code, all output will go to file.
Paulo Tavares
Hi Lokesh!
I’m new to log4j config. What I’m trying to do is add server name/hostname to the file name of the appender.
Indeed I have the same EAR deployed into 2 different servers (a cluster) using Weblogic and I need server name/hostname to be replaced by the name of each server during start up of the app.
I hope I’ve made myself clear.
Can you help here?
Here is the code:
Thanks in advance.
Paulo
Lokesh Gupta
You will need to pass hostnames at server startup parameters (usually using -D<paramaName>=<paramValue> format.)
Ram
I am seeing org.xml.sax.SAXParseException; systemId: file:/E:/Fresh%20Start/Practise%20Concepts%20Advanced/log4j-config.xml; lineNumber: 20; columnNumber: 35; The element type “appender-ref” must be terminated by the matching end-tag “”.
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:205)
at org.apache.log4j.xml.DOMConfigurator$1.parse(DOMConfigurator.java:749)
at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:871)
at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:755)
at org.apache.log4j.xml.DOMConfigurator.configure(DOMConfigurator.java:896)
at log4jdemo.Log4jFromXML.main(Log4jFromXML.java:13)
And my xml file looks like
As same as given above. Please tell me what shall i do ?
Lokesh Gupta
Orlando
Hi,
there is a possibility of a load a parameter file within properties the log4j.xml . I am using WebLogic Server within the server and have the search.properties file within the file and have routAux = / my / dir / out / so that in the log4j.xml can do something like this
within the log4j.xml x. I am using WebLogic Server within the server and have the search.properties arhivo within the file and have routAux = / my / dir / out / so that in the log4j.xml can do something like this
Lokesh Gupta
Looks like code you posted is lost.. Please paste the code inside [xml] … [/xml] tags.
Vaibhav
HI,
Thanks for posting this.
I am new to the log4j configuration. The problem I am facing is, while printing the loggers on the server log I am getting %3D, %2C type of character instead of = & , characters & so on.
I tried to put , but still problem is remaining as it is.
Can you please guide me how to resolve this issue.
When I searched on google, I came to know It’s encoding issue.
Please suggest.
Thanks,
Praful
Lokesh Gupta
You can use
<param name="Append" value="true" />
If want to backup file as well then you can use RollingFileAppender with TimeBasedRollingPolicy.
Praful
Hi below is my log4j.xml snippet, when my web application is deployed in websphere, log files are getting overwritten instead of backup files. Kindly guide me.
Lokesh Gupta
Can’t see anything…:-( Please paste the code inside [ xml ]…[ /xml ] tag (without spaces in opening and closing tag ).
4XD7
Where save the files with this configuration?
mateen
is it possible to code the entire log4j java file without xml and without properties if yes then please upload and update me
Lokesh Gupta
Read “Automatic Configuration” section in : http://logging.apache.org/log4j/2.x/manual/configuration.html
“If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.”