`

]log4j FileWatchdog工具类,用来监控文件,如有变动就执行特定的操作

阅读更多

今天看到log4j里的一个工具类,用来监控文件,如有变动就执行特定的操作,简单且有用,只需要实现一个doOnChange()方法即可。

 从这个文件可以看出,其实log4j.properties或者log4j.xml是可以实现在线修改的,不用重启服务,只需在web.xml里加一个org.springframework.web.util.Log4jConfigListener,再用<context-param>配置一个初始属性log4jRefreshInterval,即刷新log4j配置信息的间隔时间,单位是毫秒,如下:

 

1
2
3
4
5
6
7
8
9
10
11
<context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>log4j.properties</param-value>
    </context-param>
    <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>60000</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

非web应用的话需要写一个类Foo继承org.apache.log4j.varia.ReloadingPropertyConfigurator,重写doConfigure方法,直接调用org.apache.log4j.PropertyConfigurator.configureAndWatch(String, long);
然后在启动非web应用时加系统属性-Dlog4j.configuratorClass=Foo (这里要全路径),用于指定log4j Configurator的实现类。
我自己写了一个MyLog4jConfigurator,已经测试通过,如下:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
packagecom.mashiguang;
 
importjava.net.URL;
 
importorg.apache.log4j.PropertyConfigurator;
importorg.apache.log4j.spi.LoggerRepository;
importorg.apache.log4j.varia.ReloadingPropertyConfigurator;
 
publicclass MyLog4jConfigurator extendsReloadingPropertyConfigurator {
     
    PropertyConfigurator delegate = newPropertyConfigurator();
 
    @Override
    publicvoid doConfigure(URL url, LoggerRepository repository) {
        delegate.configureAndWatch(url.getFile(),1000);
    }
}

 

 

FileWatchdog源码如下:

/*

 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
// Contributors:  Mathias Bogaert
 
packageorg.apache.log4j.helpers;
 
importjava.io.File;
importorg.apache.log4j.helpers.LogLog;
 
/**
   Check every now and then that a certain file has not changed. If it
   has, then call the {<a href="http://my.oschina.net/link1212" target="_blank" rel="nofollow">@link</a>  #doOnChange} method.
 
 
   <a href="http://my.oschina.net/arthor" target="_blank" rel="nofollow">@author</a>  Ceki G&uuml;lc&uuml;
   <a href="http://my.oschina.net/u/266547" target="_blank" rel="nofollow">@since</a>  version 0.9.1 */
publicabstract class FileWatchdog extendsThread {
 
  /**
     The default delay between every file modification check, set to 60
     seconds.  */
  staticfinal public long DEFAULT_DELAY = 60000;
  /**
     The name of the file to observe  for changes.
   */
  protectedString filename;
   
  /**
     The delay to observe between every check. By default set {<a href="http://my.oschina.net/link1212" target="_blank" rel="nofollow">@link</a>
     #DEFAULT_DELAY}. */
  protectedlong delay = DEFAULT_DELAY;
   
  File file;
  longlastModif = 0;
  booleanwarnedAlready = false;
  booleaninterrupted = false;
 
  protected
  FileWatchdog(String filename) {
    this.filename = filename;
    file = newFile(filename);
    setDaemon(true);
    checkAndConfigure();
  }
 
  /**
     Set the delay to observe between each check of the file changes.
   */
  public
  voidsetDelay(longdelay) {
    this.delay = delay;
  }
 
  abstract
  protected
  voiddoOnChange();
 
  protected
  voidcheckAndConfigure() {
    booleanfileExists;
    try{
      fileExists = file.exists();
    }catch(SecurityException  e) {
      LogLog.warn("Was not allowed to read check file existance, file:["+
          filename+"].");
      interrupted = true;// there is no point in continuing
      return;
    }
 
    if(fileExists) {
      longl = file.lastModified(); // this can also throw a SecurityException
      if(l > lastModif) {           // however, if we reached this point this
    lastModif = l;              // is very unlikely.
    doOnChange();
    warnedAlready = false;
      }
    }else{
      if(!warnedAlready) {
    LogLog.debug("["+filename+"] does not exist.");
    warnedAlready = true;
      }
    }
  }
 
  public
  voidrun() {   
    while(!interrupted) {
      try{
        Thread.sleep(delay);
      }catch(InterruptedException e) {
    // no interruption expected
      }
      checkAndConfigure();
    }
  }
}

 

分享到:
评论

相关推荐

    log4j 例子全包括FileWatchdog

    2. `rolling_log_file.log` - 这很可能是`log4j`滚动日志文件的一个实例,`FileWatchdog`可能会监控此类文件,当文件达到特定大小时,会触发日志滚动操作。 3. `.project` - 另一个Eclipse项目配置文件,包含了项目...

    log4j 工具类 多个日志文件

    例如,一个系统可能有一个主要的日志文件记录常规操作,另一个专门的日志文件记录错误和异常,还可能有单独的日志文件记录特定模块的详细信息。这样有助于管理和分析日志,提高工作效率。 **实现多个日志文件的配置...

    Apache Log4j2 远程代码执行漏洞检测工具

    针对这个漏洞,开发出了专门的Apache Log4j2远程代码执行漏洞检测工具,这些工具包括针对Windows和Linux操作系统的版本。这些工具的主要目的是帮助管理员和安全专家迅速识别其环境中是否存在易受攻击的Log4j2实例。 ...

    log4j需要的jar以及properties文件

    总的来说,Log4j是一个强大且灵活的日志工具,通过`log4j-1.2.9.jar`和`log4j.properties`这两个文件,我们可以轻松地在Java项目中实现定制化的日志记录,从而提升开发效率和问题排查能力。虽然Log4j 1.x已经较为...

    log4j2漏洞检测工具

    5. **实时监控**: 部署后,工具可以持续监控系统,防止新引入的Log4j2实例带有漏洞。 **使用Log4j2漏洞检测工具** 使用这类工具通常包括以下步骤: 1. **安装与配置**: 下载并安装检测工具,根据指导文档配置好...

    C# 常用工具类 日志操作(log4net) 配置管理、字符串工具、DateTime工具、图片工具、文件工具、加密工具 等

    这些工具类通常包含对特定任务的封装,如日志记录、配置管理、字符串处理、日期时间操作、图像处理、文件操作以及安全相关的加密算法。下面将详细解释这些工具类的主要功能和应用场景。 1. **日志操作(log4net)**: ...

    log4j使用jar文件

    使用Log4j时,你需要在项目的类路径下包含`log4j.jar`文件,这是Log4j的基本运行库。然后,创建一个`log4j.properties`或`log4j.xml`配置文件,定义Logger、Appender和Layout的具体设置。例如: ```properties # ...

    log4j.jar包,和log4j.properties配置文件下载

    Log4j是一个广泛使用的Java日志记录框架,它允许开发者在应用程序中插入日志语句,以便跟踪程序的运行情况、调试错误、监控性能等。这个框架由Apache软件基金会开发,是许多Java项目的首选日志解决方案,因为它具有...

    老生常谈Log4j和Log4j2的区别(推荐)

    下面我们将从配置文件类型、核心JAR包、文件渲染和Log调用四个方面来比较Log4j和Log4j2的区别。 配置文件类型 Log4j通过一个.properties文件作为主配置文件,而Log4j2则弃用了这种方式,采用的是.xml、.json或者....

    若依框架使用的log4j2.16.0,修复log4j漏洞log4j2下载最新log4j2.16.0下载

    Log4j是一个广泛使用的Java日志记录框架,它允许开发者在应用程序中轻松地记录各种级别的日志信息,如DEBUG、INFO、WARN、ERROR等。在2021年底,一个重大的安全漏洞(CVE-2021-44228)被发现在Log4j2的早期版本中,...

    log4j-API-最新稳定版本log4j-1.2.17

    Log4j是Apache软件基金会开发的一个用于Java应用程序的日志记录工具,它提供了灵活的日志记录功能,有助于调试、性能分析和系统监控。"API"(Application Programming Interface)通常指的是开发者用来与库或框架...

    log4j-1.2.17.jar及配置文件

    《log4j-1.2.17.jar及其...理解并熟练掌握Log4j的使用,不仅可以提升开发效率,也有助于优化系统的监控和维护。通过合理配置,Log4j可以适应各种复杂的应用场景,满足不同层次的需求,从而成为Java开发者的得力助手。

    mybatis配置文件以及日志文件Log4j

    通过配置Log4j,可以打印出SQL语句及其执行时间,这对于调试和性能分析非常有帮助。例如,你可以配置Log4j的日志输出级别为DEBUG,那么在运行时,MyBatis会打印出每个SQL语句及其参数,便于查看和调试。 在实际项目...

    扫描log4j2 版本扫描log4j2 版本

    2. **版本确认**:然后,通过查看项目配置文件(如`log4j2.xml`或`log4j2.json`)或依赖管理工具(如Maven或Gradle)的配置,确定当前使用的Log4j2版本。 3. **漏洞评估**:对比已知受影响的版本列表,如CVE-2021-...

    log4j示例项目

    在Log4j项目中,通常会有一个`log4j.properties`或`log4j.xml`配置文件,用于定义日志行为。例如: ```properties # log4j.properties 示例 log4j.rootLogger=DEBUG, stdout, FILE log4j.appender.stdout=org....

    log4j漏洞扫描工具

    用户可以通过命令行界面来操作工具,执行命令`.log4jscanner.exe ./`,这里的`.log4jscanner.exe`是扫描工具的可执行文件名,`./`表示当前目录,意味着该工具将扫描当前目录下的所有JAR文件。 “参数为扫描Jar文件...

    log4j日志配置以及配置文件详解

    接下来,`log4j配置说明.txt`文件通常会提供更详细的解释和示例,包括如何配置不同的appender(如FileAppender、RollingFileAppender等),如何定义不同logger的级别,以及如何使用自定义的error handler和filter。...

    log4j 写多个日志文件,按照日期每天都记

    1. **配置多个Appender**:`log4j`允许定义多个Appender,每个Appender可以有不同的输出目的地,如控制台、文件、数据库等。在我们的需求中,我们需要为每一天创建一个单独的日志文件,所以需要为每一天定义一个...

    Log4j2简介及与Log4j效率对比

    10. **优化的并发支持**:Log4j2利用Java 5提供的并发特性,能够在较低级别上执行锁定操作,有效避免了Log4j 1.x中出现的死锁问题。 ### Log4j2与Log4j效率对比 #### 测试环境与方法 为了准确评估Log4j2与Log4j...

    log4j-1.2.17的jar包以及依赖包,还有一份log4j的配置文件,输出到控制台和文件夹两种配置

    1. **log4j-1.2.17.jar**: 这是Log4j的主要库文件,包含了所有Log4j的类和接口。通过这个库,开发者可以方便地在代码中插入日志语句,记录程序运行时的信息、警告、错误等。 2. **commons-logging-1.2.jar**: 这是...

Global site tag (gtag.js) - Google Analytics