Get the name of the package from which a SQL query

2019-02-26 16:47发布

问题:

I am using jdbcdslog with log4j logging engine in a webapp. I am able to log SQL queries that are executed. I want to know how to get the name of the package from which the query was fired. So that I can separate out the Log information, and know where a query cam from just by looking at the log, rather than going through the code.

I tried to use the %C parameter in PatternLayout of Log4j to get the package name as mentioned here

But the output I get is

2013-07-30-main--INFO -org.jdbcdslog.StatementLogger:java.sql.Statement.executeQuery: SELECT id, first, last, age FROM Employees;

As you can see, the SQL query is logged, but the class it gave out is org.jdbcdslog.StatementLogger. Which is not what is desired, Since I want the name of the class the query was fired from.

I am using the following setting in Log4j.properties file

log4j.appender.S.layout.ConversionPattern=%d{yyyy-MM-dd}-%t-%x-%-5p-%C:%m%n

It happens because jdbcdslog wraps the connection to the JDBC driver. I want to know how to get the name of the class where the query was fired from.

回答1:

From the http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html I cant see any place where you can specify a variable for originating method. Also looking through the events log4j passes around it doesnt look like that information gets passed down the chain of events.(http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/spi/LoggingEvent.html).

However if you really need this functionality you could probably pull off some workaround involving implementing your own DataSourceProxyBase. I downloaded the jdbcdslog source from their download page, It looks like you can extend and override some methods from the DataSourceProxyBase class and add in your own logger. Then point your setup to use that data source proxy.

<bean id="dataSourceActual" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName">
        <value>java:comp/env/jdbc/MyDatasource</value>
    </property>
</bean>

<bean id="dataSource" class="com.me.MySoureConnectionPoolDataSourceProxy">
    <property name="targetDSDirect" ref="dataSourceActual" />
</bean>

If you download the source you can start following their program around and see what you would need to override to implement what you need. A good starting place might be the class PooledConnectionLoggingProxy