mybatis配置日志实现框架

使用mybatis + logback通过配置appender设置指定sql日志追加到指定文件中

mybatis配置

<!-- spring-mybatis.xml -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	<property name="driverClassName" value="${jdbc.driver}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
	<property name="initialSize" value="${jdbc.initialSize}"></property>
	<property name="maxActive" value="${jdbc.maxActive}"></property>
	<property name="maxIdle" value="${jdbc.maxIdle}"></property>
	<property name="minIdle" value="${jdbc.minIdle}"></property>
	<property name="maxWait" value="${jdbc.maxWait}"></property>
	<property name="validationQuery" value="${jdbc.validationQuery}"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource" />
	<property name="mapperLocations" value="classpath:com/eoekun/dao/**/mapper/*.xml"></property>
	<property name="typeAliasesPackage" value="com.eoekun.entity" />
	<property name="configLocation" value="classpath:spring/mybatis-config.xml"></property>
</bean>

mybatis-config.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration   
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<setting name="logImpl" value="SLF4J" />
	</settings>
</configuration>

logback配置

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
	<property name="log_dir" value="/data/logs/apps/8308-gpspf/" />
	<property name="maxHistory" value="3" />
	<property name="charset" value="utf-8" />
	<appender name="SQL" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log_dir}/sql-%d{yyyy-MM-dd}.log
			</fileNamePattern>
			<maxHistory>${maxHistory}</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
		</encoder>
	</appender>
	<!-- sql -->
	<logger name="java.sql" level="DEBUG" additivity="false">
		<appender-ref ref="SQL" />
	</logger>
	<logger name="org.apache.ibatis" level="DEBUG" additivity="false">
		<appender-ref ref="SQL" />
	</logger>
	<logger name="org.mybatis" level="DEBUG" additivity="false">
		<appender-ref ref="SQL" />
	</logger>
	<logger name="com.eoekun.dao" level="DEBUG" additivity="false">
		<appender-ref ref="SQL" />
	</logger>
</configuration>

参考

  1. XML 映射配置文件
  2. logback