Question

I am using spring org.springframework.jdbc.core.JdbcTemplate and org.springframework.jdbc.core.simple.SimpleJdbcCall for my database queries. I am using log4j2.xml for logging. I want to log all my sql queries and their DB result in db.log file.

I have tried to used following logger in my log4j2.xml file but it did not log anything in db.log file. I tried level="TRACE" and level="debug" but both not working.

    <RollingFile name="db" fileName="${sys:catalina.home}/logs/db.log"
        filePattern="${sys:catalina.home}/logs/$${date:yyyy-MM-dd}/db-%d{yyyy-MM-dd}-%i.log.gz">
        <PatternLayout
            pattern="%d{dd/MM/yyyy HH:mm:ss,SSS} [%X{cartID}] [%X{sessionId}] [%p] [%t] [%c] (%F:%L)  - %m%n" />
        <Policies>
            <TimeBasedTriggeringPolicy interval="1"
                modulate="true" />
            <SizeBasedTriggeringPolicy size="10 MB" />
        </Policies>
    </RollingFile>
</Appenders>
<Loggers>
    <Logger name="org.springframework.jdbc.core.JdbcTemplate" level="TRACE" additivity="false">
        <Appender-Ref ref="db" />
    </Logger>

In our java classes we are using following sql

String sQuery = "select count(*) from impersonation_requests where ir_eid = ? and  ir_tmp_userid = ?";
String value =  template
                .queryForObject(sQuery, new Object[] { passwordInfo.getEid(),
                        passwordInfo.getUserId() }, String.class);

Here var template is instance variable of org.springframework.jdbc.core.JdbcTemplate

I want to see sQuery and value entries in my db.log file. Can we achieve this using JdbcTemplate or I need to implement logger in all my DAO classes and log sQuery and values in each class where I am using JdbcTemplate. I want to avoid this approach. Please suggest.

Was it helpful?

Solution

I'd say name="org.springframework.jdbc.core.JdbcTemplate" is very 'strict'. Try this category:

org.springframework.jdbc

OTHER TIPS

<Logger name="org.springframework.jdbc.core.JdbcTemplate" level="TRACE" additivity="false">
      <Appender-Ref ref="db" />
</Logger>

This will definitely work. debug and trace both level will work. Only thing is JDBCTemplate is using common-logging API to log. And if you are using log4j in your application, you will have to add common logging bridge for the same.

Add following in your pom.xml

 <dependency>
     <groupId>org.apache.logging.log4j</groupId>
     <artifactId>log4j-jcl</artifactId>
     <version>2.0-rc1</version>
 </dependency>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top