1. 首先在pom.xml里引入依赖 ```xml
    1. <dependency>
    2. <groupId>org.slf4j</groupId>
    3. <artifactId>slf4j-log4j12</artifactId>
    4. <version>1.7.25</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>log4j</groupId>
    8. <artifactId>log4j</artifactId>
    9. <version>1.2.17</version>
    10. </dependency>
  1. 2. web.xml配置
  2. ```xml
  3. <!-- 加载log4j配置文件 -->
  4. <context-param>
  5. <param-name>log4jConfigLocation</param-name>
  6. <param-value>classpath:log4j.properties</param-value>
  7. </context-param>
  8. <listener>
  9. <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  10. </listener>

备注:Log4jConfigListener这种配置方式,只适用于spring4.x的,spring5.x的就不适用了哦。

  1. 编写 log4j.properties 文件 ```latex

    \u5B9A\u4E49LOG\u8F93\u51FA\u7EA7\u522B

    log4j.rootLogger=DEBUG,INFO,Console,File log4j.appender.rootFileApd.Encoding=UTF-8

    \u5B9A\u4E49\u65E5\u5FD7\u8F93\u51FA\u76EE\u7684\u5730\u4E3A\u63A7\u5236\u53F0

    log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out

    \u53EF\u4EE5\u7075\u6D3B\u7684\u6307\u5B9A\u65E5\u5FD7\u8F93\u51FA\u683C\u5F0F\uFF0C\u4E0B\u9762\u4E00\u884C\u662F\u6307\u5B9A\u5177\u4F53\u7684\u683C\u5F0F

    log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%c]-%m%n

mybatis\u663E\u793ASQL\u8BED\u53E5\u65E5\u5FD7\u914D\u7F6E

log4j.logger.org.mybatis=DEBUG

控制台打印sql语句

log4j.logger.cn.appsys.dao=DEBUG

\u6587\u4EF6\u5927\u5C0F\u5230\u8FBE\u6307\u5B9A\u5C3A\u5BF8\u7684\u65F6\u5019\u4EA7\u751F\u4E00\u4E2A\u65B0\u7684\u6587\u4EF6

log4j.appender.File=org.apache.log4j.RollingFileAppender

\u6307\u5B9A\u8F93\u51FA\u76EE\u5F55

log4j.appender.File.File=logs/ssm.log

\u5B9A\u4E49\u6587\u4EF6\u6700\u5927\u5927\u5C0F

log4j.appender.File.MaxFileSize=10MB

\u8F93\u51FA\u6240\u6709\u65E5\u5FD7\uFF0C\u5982\u679C\u6362\u6210DEBUG\u8868\u793A\u8F93\u51FADEBUG\u4EE5\u4E0A\u7EA7\u522B\u65E5\u5FD7

log4j.appender.File.Threshold=ALL log4j.appender.File.layout=org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm|\:ss}][%c]%m%n ``` 备注:#控制台打印sql语句,这里的cn.appsys.dao是要配置你dao层的包名
log4j.logger.cn.appsys.dao=DEBUG
遇到一个小插曲:

  1. logger.debug(“后台管理” +o.getUserCode() + “登录”);打印的时候中文乱码,

配置Tomcat VM options值为:-Dfile.encoding=UTF-8就可以
image.png

  1. logger.debug不输出东西,解决方案是在log4j.properties 里加上log4j.rootLogger=DEBUG,INFO,Console,File

就行,之前少了DEBUG。