Search code examples
javalogginginterfaceapache-commonsapache-commons-logging

What is Logging, and how is Apache Commons logging used?


What information would a web application server wish to log, and why?

From what I understand

org.apache.commons.logging.Log

is an interface that abstracts the functionality provided by other Logging classes, and the same applies to the interface LogFactory.

Code I am trying to understand has -

Log auditLogger = LogFactory.getLog(someString);

How is the String someString used to identify what LogFactory to generate? How can I see the implementation of the Log and LogFactory classes being used?


Solution

  • The string is an arbitrary identifier which we can use to redirect or filter the logging output. One common approach is to use the className, e.g.,

    Log auditLogger = LogFactory.getLog(MyCurrentClass.class);
    

    As you said, commons-logging is a facade which defaults to java.util.logging if no other logging library is supplied. I would recommend to put a logging implementation such as log4j, logback, or slf4j in the classpath.

    Assuming you put e.g., log4j there you can control the logging output using a configuration file log4j.xml, such as:

    <?xml version="1.0" encoding="UTF-8"?>
    <log4j:configuration>
    
        <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
            ..... 
        </appender>
    
    
        <!-- Send debug information from "com.company.MyCurrentClass" to CONSOLE -->
        <logger name="com.company.MyCurrentClass">
            <level value="DEBUG"/>
            <appender-ref ref="CONSOLE"/>
        </logger>
    
    </log4j:configuration>