Log4j Refer



DEBUG is the lowest restricted java logging level and we should write everything we need to debug an application, this java logging mode should only be used on Development and Testing environment and must not be used in production environment.

INFO is more restricted than DEBUG java logging level and we should log messages which are informative purpose like Server has been started, Incoming messages, outgoing messages etc in INFO level logging in java.

WARN is more restricted than INFO java logging level and used to log warning sort of messages e.g. Connection lost between client and server. Database connection lost, Socket reaching to its limit. These messages and java logging level are almost important because you can setup alert on these logging messages in java and let your support team monitor health of your java application and react on this warning messages. In Summary WARN level is used to log warning message for logging in Java.

ERROR is the more restricted java logging level than WARN and used to log Errors and Exception, you can also setup alert on this java logging level and alert monitoring team to react on this messages. ERROR is serious for logging in Java and you should always print it.

FATAL java logging level designates very severe error events that will presumably lead the application to abort. After this mostly your application crashes and stopped.

OFF java logging level has the highest possible rank and is intended to turn off logging in Java.









here is the log4j.xml file:

<?xml version=”1.0″ encoding=”UTF-8″ ?>

<!DOCTYPE log4j:configuration SYSTEM “log4j.dtd”>

<log4j:configuration xmlns:log4j=’http://jakarta.apache.org/log4j/’&gt;



<!– ============================== –>

<!– Append messages to the console –>

<!– ============================== –>



<appender name=”console” class=”org.apache.log4j.ConsoleAppender”>

<param name=”Target” value=”System.out” />


<layout class=”org.apache.log4j.PatternLayout”>

<!– The default pattern: Date Priority [Category] Message\n –>

<param name=”ConversionPattern” value=”[AC – %5p] [%d{ISO8601}] [%t] [%c{1} – %L] %m%n” />




<appender name=”logfile” class=”org.apache.log4j.RollingFileAppender”>

<param name=”File” value=”./logs/server.log” />

<param name=”MaxFileSize” value=”1000KB” />

<param name=”MaxBackupIndex” value=”2″ />

<layout class=”org.apache.log4j.PatternLayout”>

<param name=”ConversionPattern” value=”[AC – %-5p] {%d{dd.MM.yyyy – HH.mm.ss}} %m%n” />




<appender name=”payloadAppender” class=”org.apache.log4j.RollingFileAppender”>

<param name=”File” value=”./logs/payload.log” />

<param name=”MaxFileSize” value=”1000KB” />

<param name=”MaxBackupIndex” value=”10″ />

<layout class=”org.apache.log4j.PatternLayout”>

<param name=”ConversionPattern” value=”[AC – %-5p] {%d{dd.MM.yyyy – HH.mm.ss}} %m%n” />




<appender name=”errorLog” class=”org.apache.log4j.RollingFileAppender”>

<param name=”File” value=”./logs/error.log” />

<param name=”MaxFileSize” value=”1000KB” />

<param name=”MaxBackupIndex” value=”10″ />

<layout class=”org.apache.log4j.PatternLayout”>

<param name=”ConversionPattern” value=”[AC – %-5p] {%d{dd.MM.yyyy – HH.mm.ss}} %m%n” />




<appender name=”traceLog”


<param name=”File” value=”./logs/trace.log” />

<param name=”MaxFileSize” value=”1000KB” />

<param name=”MaxBackupIndex” value=”20″ />


<layout class=”org.apache.log4j.PatternLayout”>

<param name=”ConversionPattern”

value=”[AccessControl – %-5p] {%t: %d{dd.MM.yyyy – HH.mm.ss,SSS}} %m%n” />




<appender name=”traceSocketAppender” class=”org.apache.log4j.net.SocketAppender”>

<param name=”remoteHost” value=”localhost” />

<param name=”port” value=”4445″ />

<param name=”locationInfo” value=”true” />



<logger name=”TraceLogger”>

<level value=”trace” /> <!– Set level to trace to activate tracing –>

<appender-ref ref=”traceLog” />



<logger name=”org.springframework.ws.server.endpoint.interceptor”>

<level value=”DEBUG” />

<appender-ref ref=”payloadAppender” />




<level value=”error” />

<appender-ref ref=”errorLog” />









up vote64down vote The root logger resides at the top of the logger hierarchy. It is exceptional in three ways:

·         it always exists,

·         its level cannot be set to null

·         it cannot be retrieved by name.

The rootLogger is the father of all appenders. Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy (including rootLogger)

For example, if the console appender is added to the root logger, then all enabled logging requests will at least print on the console. If in addition a file appender is added to a logger, say L, then enabled logging requests for L and L’s children will print on a file and on the console. It is possible to override this default behavior so that appender accumulation is no longer additive by setting the additivity flag to false.

From the log4j manual

To sum up:

If you want not to propagate a logging event to the parents loggers (say rootLogger) then add the additivity flag to false in those loggers. In your case:

<logger name=”org.springframework.ws.server.endpoint.interceptor”


<level value=”DEBUG” />

<appender-ref ref=”payloadAppender” />


In standard log4j config style (which I prefer to XML):

log4j.logger.org.springframework.ws.server.endpoint.interceptor = INFO, payloadAppender

log4j.additivity.org.springframework.ws.server.endpoint.interceptor = false

Hope this helps.





up vote54down voteaccepted What you need to do is have a single <logger> definition with a defined level of INFO, but in your two appender definitions, you set their thresholds accordingly, e.g.

<appender name=”ERROR_FILE”>

<param name=”Threshold” value=”ERROR”/>



<appender name=”GENERAL”>

<param name=”Threshold” value=”INFO”/>


You then add both appenders to your logger:

<logger name=”com.acme”>

<level value=”INFO”/>

<appender-ref ref=”ERROR_FILE”/>

<appender-ref ref=”GENERAL”/>


Log entries now going to the logger will get sent to both appenders, but since they have different independent thresholds, the ERROR_FILE appender will only log ERROR and above.



Full working solution including the date in the filename:

<appender name=”InfoFileAppender” class=”org.apache.log4j.rolling.RollingFileAppender”>

<rollingPolicy class=”org.apache.log4j.rolling.TimeBasedRollingPolicy”>

<param name=”FileNamePattern” value=”/var/output/Info_%d{ddMMyyyy}.log” />


<layout class=”org.apache.log4j.PatternLayout”>

<param name=”ConversionPattern” value=”%d{HH:mm:ss} %-5p %t %c{2} – %m%n” />


<filter class=”org.apache.log4j.varia.LevelRangeFilter”>

<param name=”levelMin” value=”INFO” />

<param name=”levelMax” value=”INFO” />




<appender name=”ErrorFileAppender” class=”org.apache.log4j.rolling.RollingFileAppender”>

<param name=”Threshold” value=”ERROR” />

<rollingPolicy class=”org.apache.log4j.rolling.TimeBasedRollingPolicy”>

<param name=”FileNamePattern” value=”/var/output/Error_%d{ddMMyyyy}.log” />


<layout class=”org.apache.log4j.PatternLayout”>

<param name=”ConversionPattern” value=”%d{HH:mm:ss} %-5p %t %c{2} – %m%n” />




<level value=”INFO” />

<appender-ref ref=”InfoFileAppender” />

<appender-ref ref=”ErrorFileAppender” />






94down vote I’d say you’re probably fine with util.logging for the needs you describe.

For a good decision tree, have a look at Log4j vs java.util.logging

Question One : Do you anticipate a need for any of the clever handlers that Log4j has that JUL does not have, such as the SMTPHandler, NTEventLogHandler, or any of the very convenient FileHandlers?

Question Two : Do you see yourself wanting to frequently switch the format of your logging output? Will you need an easy, flexible way to do so? In other words, do you need Log4j’s PatternLayout?

Question Three : Do you anticipate a definite need for the ability to change complex logging configurations in your applications, after they are compiled and deployed in a production environment? Does your configuration sound something like, “Severe messages from this class get sent via e-mail to the support guy; severe messages from a subset of classes get logged to a syslog deamon on our server; warning messages from another subset of classes get logged to a file on network drive A; and then all messages from everywhere get logged to a file on network drive B”? And do you see yourself tweaking it every couple of days?

If you can answer yes to any of the above questions, go with Log4j. If you answer a definite no to all of them, JUL will be more than adequate and it’s conveniently already included in the SDK.

That said, pretty much every project these days seems to wind up including log4j, if only because some other library uses it.


Log4j has been around for a long time, and it works very well. I have no scientific study to back it, but based on what I’ve seen at a large number of clients, it is easily the logging framework that I see used more than any other. It has been around for a long time, and not been replaced by the Next Big Logging Framework, which says something.

It is dead simple to set up, and easy to learn the basic appenders (outputs). There are a whole host appenders that are available, including:

  1. ConsoleAppender
  2. DailyRollingFileAppender
  3. ExternallyRolledFileAppender
  4. FileAppender
  5. JDBCAppender
  6. JMSAppender
  7. NTEventLogAppender
  8. RollingFileAppender
  9. SMTPAppender
  10. SocketAppender
  11. SyslogAppender
  12. TelnetAppender
  13. WriterAppender

Plus others. It isn’t difficult to write your own appender either. Additionally there is a great deal of flexibility in each of the appenders that allow you to control specifically what is output in your log.

One note, I had a series of classloader problems when I used apache commons logging in addition to log4j. It was only for one specific application, but I found it simpler to use log4j alone, rather than to have the flexibility offered when using an abstraction layer like commons logging.

See this article for more details:

Good luck!




58down voteaccepted Changing the log level is simple; modifying other portions of the configuration will pose a more in depth approach.

LogManager.getRootLogger().setLevel(Level.DEBUG);The changes are permanent through the life cyle of the Logger. On reinitialization the configuration will be read and used as setting the level at runtime does not persist the level change.

UPDATE: If you are using Log4j 2 you should remove the calls to setLevel per the documentation as this can be achieved via implementation classes.

Calls to logger.setLevel() or similar methods are not supported in the API. Applications should remove these. Equivalent functionality is provided in the Log4j 2 implementation classes but may leave the application susceptible to changes in Log4j 2 internals.




216down voteaccepted You can add/remove Appender programmatically to Log4j:

ConsoleAppender console = new ConsoleAppender(); //create appender  //configure the appender  String PATTERN = “%d [%p|%c|%C{1}] %m%n”;  console.setLayout(new PatternLayout(PATTERN));   console.setThreshold(Level.FATAL);  console.activateOptions();  //add appender to any Logger (here is root)  Logger.getRootLogger().addAppender(console);   FileAppender fa = new FileAppender();  fa.setName(“FileLogger”);  fa.setFile(“mylog.log”);  fa.setLayout(new PatternLayout(“%d %-5p [%c{1}] %m%n”));  fa.setThreshold(Level.DEBUG);  fa.setAppend(true);  fa.activateOptions();   //add appender to any Logger (here is root)  Logger.getRootLogger().addAppender(fa);  //repeat with all other desired appendersI’d suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with

Logger.getRootLogger().getLoggerRepository().resetConfiguration();and start with adding your own. You need log4j in the classpath of course for this to work.

You can take any Logger.getLogger(…) you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).

If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:

Logger fizz = LoggerFactory.getLogger(“com.fizz”)will give you a logger for the category “com.fizz”.
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to Logger.getLogger(“com.fizz”).addAppender(newAppender) then logging from fizz will be handled by alle the appenders from the root logger and the newAppender.
You don’t create Loggers with the configuration, you just provide handlers for all possible categories in your system.




up vote22down voteaccepted You can easily invoke log4j’s API programmatically, e.g.

FileAppender appender = new FileAppender();

// configure the appender here, with file location, etc



Logger logger = getRootLogger();


The logger can be the root logger as in this example, or any logger down the tree. Your unit test can add its custom appender during steup, and remove the appender (using removeAppender()) during teardown.








up vote69down vote This should get you started:

log4j.rootLogger=QuietAppender, LoudAppender, TRACE

# setup A1






# setup A2








log4j.rootLogger=ERROR, logfile






log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x – %m\n


log4j.logger.foo.bar.Baz=DEBUG, myappender







log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x – %m\n




up vote4down voteaccepted The simplest option is to programmatically add your appender once your GUI has been initialised. Something like this:

Logger.getRootLogger().addAppender(yourTextAreaAppender);EDIT: To only log the INFO level do this:

yourTextAreaAppender.addFilter(new Filter() {    @Override    public int decide(LoggingEvent event) {        if (event.getLevel().equals(Level.INFO)) {            return ACCEPT;        } else {            return DENY;        }    }});

shareimprove this answer