Spring项目配置log4j日志功能

一,添加log4j依赖包

可从官网上下载该依赖包log4j-x.x.xx.jar,下载后 build path,添加依赖包如使用maven,可以添加如下依赖

    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

二,创建 log4j.properties 配置文件

log4j.properties配置文件用来配置 日志的输出格式、输出的地址....

### set log levels ###
log4j.rootLogger = INFO, D, E

log4j.appender.D = org.apache.log4j.RollingFileAppender
log4j.appender.D.File =${scheduleProject}WEB-INF/logs/schedule.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.MaxFileSize = 50000KB
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

log4j.appender.E = org.apache.log4j.RollingFileAppender
log4j.appender.E.File = ${scheduleProject}WEB-INF/logs/schedule.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.MaxFileSize = 50000KB
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss}  [ %l\:%c\:%t\:%r ] - [ %p ]  %m%n

三,在web.xml文件中 配置 加载 log4j.properties的属性

<!-- 加载log4j的配置文件log4j.properties -->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.properties</param-value>
    </context-param>

    <!-- 设定刷新日志配置文件的时间间隔,这里设置为10s -->
    <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>10000</param-value>
    </context-param>

    <!-- 加载Spring框架中的log4j监听器Log4jConfigListener -->
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <!-- 为避免项目间冲突,定义唯一的 webAppRootKey -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>scheduleProject</param-value>
    </context-param>

四,在代码中使用log4j进行日志记录

public class Test {
    private static Logger logger = Logger.getLogger(Test.class);
    public static void main(String[]args)
    {
        logger.info("23423");
        logger.warn("sdfsdf");
    }
}

五,参考资料

 Log4j 日志配置示例详解

Spring MVC中 log4j日志文件配置相对路径

posted on 2017-09-02 11:46  大朋展翅  阅读(1905)  评论(0编辑  收藏  举报

导航