springlogging

How to Log in Spring?


I've never been using logging, so I'm pretty ignorant about it. Anyway I've a Spring controller and I thought that it was as easy as adding this to the controller's class:

private Logger logger = LoggerFactory.getLogger(this.getClass());

where logger is org.slf4j.Logger and to log use:

logger.info("mainpage");

but nothing appears on the eclipse console. How do I do it?

I didn't configure log4j or anything.


Solution

  • If you want to configure log4j, you will need the jar first. Then, place this in your web.xml:-

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.xml</param-value>
    </context-param>
    
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
    

    In this example, you will need to create your log4j.xml, something like this:-

    <?xml version="1.0" encoding="UTF-8" ?>
    
    <log4j:configuration>
        <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
            <param name="Target" value="System.out" />
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern" value="[%-5p] [%c{1}] [%M:%L] - %m%n" />
            </layout>
        </appender>
    
        <root>
            <priority value="debug" />
            <appender-ref ref="consoleAppender" />
        </root>
    </log4j:configuration>