Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log spring JdbcTemplate sql queries and DB response in log file using log4j2

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.

like image 770
vivek Avatar asked Mar 21 '14 09:03

vivek


People also ask

Which method can be used to retrieve a JdbcTemplate while using JdbcDaoSupport?

Example With JdbcDaoSupport And you can get the JdbcTemplate by using a getJdbcTemplate() method.

Which method is used to get objects from JdbcTemplate?

In Java's Spring framework, we can use jdbcTemplate. queryForObject() to get a single row record from the database, and convert the row into an object (i.e. POJO or your entity class) via the row mapper feature.

How does JdbcTemplate get single record?

Query for Single Row In Spring, we can use jdbcTemplate. queryForObject() to query a single row record from database, and convert the row into an object via row mapper. 1.2 Spring BeanPropertyRowMapper , this class saves you a lot of time for the mapping.


1 Answers

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

org.springframework.jdbc
like image 132
Artem Bilan Avatar answered Sep 20 '22 00:09

Artem Bilan