从tomcat官网(https://tomcat.apache.org/tomcat-7.0-doc/logging.html)上找了下,修改一些配置、替换扩展包即可使用log4j输出catalian.out。
在$CATALINA_BASE/lib下创建log4j.properties文件
log4j.properties的内容如下:
log4j.rootLogger = INFO, CATALINA # Define all the appenders log4j.appender.CATALINA = org.apache.log4j.DailyRollingFileAppender log4j.appender.CATALINA.File = ${catalina.base}/logs/catalina.out log4j.appender.CATALINA.Append = true log4j.appender.CATALINA.Encoding = UTF-8 # Roll-over the log once per day log4j.appender.CATALINA.DatePattern = '.'yyyy-MM-dd log4j.appender.CATALINA.layout = org.apache.log4j.PatternLayout #log4j.appender.CATALINA.layout.ConversionPattern = %d [%t] %-5p %c- %m%n log4j.appender.CATALINA.layout.ConversionPattern =%d{yyyy-MM-dd HH:mm:ss.SSS} %p [%t] %c | %m%n # configure customed log to catalina.out log4j.logger.com.xxxxx = WARN, CATALINA log4j.logger.org.apache = WARN, CATALINA log4j.logger.org.mybatis = WARN, CATALINA log4j.logger.java.sql = WARN, CATALINA log4j.logger.org.springframework = WARN, CATALINA
更新tomcat相关jar包
下载log4j-1.2.17.jar(http://www.apache.org/dist/logging/log4j/1.2.17/)
下载tomcat7的2个jar包:tomcat-juli.jar 和 tomcat-juli-adapters.jar(http://www.apache.org/dist/tomcat/tomcat-7/v7.0.69/bin/extras/ 最好和tomcat版本对应)
把log4j-1.2.17.jar和tomcat-juli-adapters.jar放到$CATALINA_HOME/lib下;用新下载的tomcat-juli.jar包替换掉$CATALINA_HOME/bin/tomcat-juli.jar包。
删除$CATALINA_BASE/conf/logging.properties。
重启tomcat
关于默认的catalina日志格式
如果只想修改tomcat默认的日志格式,替换掉默认的java.util.logging.SimpleFormatter
即可。SimpleFormatter类里format格式为LoggingSupport.getSimpleFormat()
,它的具体值是:”%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%6$s%n”,其中时间格式可能不是我们期望的,还有里面有个换行%n。比如想改为类似上面log4j的时间格式,可自己重写一个替换类(com.xxx.LogFormatter),format设为”%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$s %2$s %5$s%6$s%n”。修改$CATALINA_BASE/conf/logging.properties
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
改为如下:
java.util.logging.ConsoleHandler.formatter = com.xxx.LogFormatter org.apache.juli.FileHandler.formatter = com.xxx.LogFormatter