why do we need root and logger in log4j.xml

It is enough.

In log4j a logger is associated with a package or sometimes with a particular class. Package/class of a logger is defined by the attribute “name”. A logger logs messages in its package and also in all the child packages and their classes. The only exception is the root logger that logs messages for the all classes in the application.

A logger also has level and may have one or many appenders (logging destinations) attached to it.

In the next example we have two loggers:

  • the root logger that logs messages with level INFO or above in the all packages to the various destinations: console, e-mail and file,
  • “com.foo” logger that logs messages with level WARN or above in package “com.foo” and its child packages to the another file.
<log4j:configuration>
    <!-- Declaration of appenders FILE, MAIL, CONSOLE and ANOTHERFILE -->
    ...
    <!-- -->

    <logger name="com.foo">
        <level value="warn"/>
        <appender-ref ref="ANOTHERFILE" /> 
    </logger>
    <root> 
        <priority value ="info" />
        <appender-ref ref="FILE" /> 
        <appender-ref ref="MAIL" />
        <appender-ref ref="CONSOLE" /> 
    </root>
</log4j:configuration>

You should read more about the log4j basics.

Leave a Comment