一,Hibernate日志问题
工程使用SLF4J,但日志文件一直没有看到Hibernate相关日志及showsql
二,Logback文件配置
修改Hibernate 日志输出指定为SLF4J,当修改了LOGBACK.xml 的日志输出文件后仍然也没看到hibernate相应日志
logback.xml 关键信息:
<!-- show parameters for hibernate sql 专为 Hibernate 定制 --> <logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE" /> <logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG" /> <logger name="org.hibernate.SQL" level="DEBUG" /> <logger name="org.hibernate.engine.QueryParameters" level="DEBUG" /> <logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" />
Spring 配置show sql:
<prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop>
启动没有看到Hibernate日志!(万马奔腾,种类=草泥马)
三,原因排查
Hibernate 默认使用日志jar为 org.jboss.logging
查看关键代码如下:
org.jboss.logging.LoggerProviders static final String LOGGING_PROVIDER_KEY = "org.jboss.logging.provider"; final ClassLoader cl = LoggerProviders.class.getClassLoader(); try { // Check the system property final String loggerProvider = AccessController.doPrivileged(new PrivilegedAction<String>() { public String run() { return System.getProperty(LOGGING_PROVIDER_KEY); } }); if (loggerProvider != null) { if ("jboss".equalsIgnoreCase(loggerProvider)) { return tryJBossLogManager(cl, "system property"); } else if ("jdk".equalsIgnoreCase(loggerProvider)) { return tryJDK("system property"); } else if ("log4j2".equalsIgnoreCase(loggerProvider)) { return tryLog4j2(cl, "system property"); } else if ("log4j".equalsIgnoreCase(loggerProvider)) { return tryLog4j(cl, "system property"); } else if ("slf4j".equalsIgnoreCase(loggerProvider)) { return trySlf4j("system property"); } } } catch (Throwable t) { // nope... }
四,解决方案
通过设置环境变量为log 指定类型,方式如下:
1,MAIN方法启动的可设定变量
System.setProperty("org.jboss.logging.provider", "slf4j");
2,WEB 注解方式
@WebListener public class ContextListenerExample implements ServletContextListener { public void contextInitialized(ServletContextEvent e){ System.setProperty("org.jboss.logging.provider", "slf4j"); } }
3,WEB.XML中配置WebApplicationInitializer
@Override public void onStartup(ServletContext servletContext) throws ServletException { System.setProperty("org.jboss.logging.provider", "slf4j"); }
4,spring 配置方式
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetObject"> <!-- System.getProperties() --> <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetClass" value="java.lang.System"/> <property name="targetMethod" value="getProperties"/> </bean> </property> <property name="targetMethod" value="putAll"/> <property name="arguments"> <!-- The new Properties --> <util:properties> <prop key="org.jboss.logging.provider">slf4j</prop> </util:properties> </property> </bean>
Spring 进行改方法System.getProperties() 方法的调用,NB,Spring 地球都是你的了!