log4j - DailyRollingFileAppender,文件不每小时滚动

发布于 2024-12-10 06:27:44 字数 917 浏览 0 评论 0原文

我有以下简单的 Test 类,用于 DailyRollingFileAppender 每小时滚动一次日志文件。我面临的问题是,即使我将其设置为“.”yyyy-MM-dd-HH,它似乎也不会每小时滚动到新的日志文件。知道我在代码中哪里做错了吗?

public class Test {
  static Logger logger = Logger.getLogger(Test.class);

  public static void main(String args[]) throws Exception {
      String pattern = "%-20d{dd MMM yyyy HH:mm:ss} [%-5p] - %m%n";

    PatternLayout patternLayout = new PatternLayout(pattern);  

    //CREATE APPENDER.       
    DailyRollingFileAppender myAppender = new DailyRollingFileAppender(patternLayout, "TestOrig.log", "'.'yyyy-MM-dd-HH");

    //ADD APPENDER & LEVEL.
    logger.addAppender(myAppender);
    logger.setLevel   ((Level) Level.DEBUG);


//WRITE MESSAGES.
logger.debug("Successful");
logger.info ("Failed" );
logger.warn ("Failed" );
logger.error("Successful");
logger.fatal("Failed"); 

    while(true)
    {           
        Thread.sleep(1000);
    } 
  }
}

I have the following simple Test class for DailyRollingFileAppender to rolls the log file every hour. The problem I am facing is that, it doesn't seem to roll over to new log file every hour even though I have set that to '.'yyyy-MM-dd-HH. Any idea where in the code I did wrongly?

public class Test {
  static Logger logger = Logger.getLogger(Test.class);

  public static void main(String args[]) throws Exception {
      String pattern = "%-20d{dd MMM yyyy HH:mm:ss} [%-5p] - %m%n";

    PatternLayout patternLayout = new PatternLayout(pattern);  

    //CREATE APPENDER.       
    DailyRollingFileAppender myAppender = new DailyRollingFileAppender(patternLayout, "TestOrig.log", "'.'yyyy-MM-dd-HH");

    //ADD APPENDER & LEVEL.
    logger.addAppender(myAppender);
    logger.setLevel   ((Level) Level.DEBUG);


//WRITE MESSAGES.
logger.debug("Successful");
logger.info ("Failed" );
logger.warn ("Failed" );
logger.error("Successful");
logger.fatal("Failed"); 

    while(true)
    {           
        Thread.sleep(1000);
    } 
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烟燃烟灭 2024-12-17 06:27:44

使用@Singleton 和@Schedule 为您的计时器服务创建一个类似ejb cron 的时间表。

import javax.ejb.Schedule;
import javax.ejb.Singleton;


@Singleton
public class Cron {
        static Logger logger = Logger.getLogger(Test.class);
    @Schedule(second="0", minute="0", hour="0", dayOfWeek="*", persistent=false)
    public void rollLogs() {
        logger.info("midnight");
    }
}

Use @Singleton and @Schedule to create an ejb cron like schedule for your timer service.

import javax.ejb.Schedule;
import javax.ejb.Singleton;


@Singleton
public class Cron {
        static Logger logger = Logger.getLogger(Test.class);
    @Schedule(second="0", minute="0", hour="0", dayOfWeek="*", persistent=false)
    public void rollLogs() {
        logger.info("midnight");
    }
}
撩心不撩汉 2024-12-17 06:27:44

我在这里没有看到任何错误。当我尝试了几分钟后,我可以看到这正在创建文件。

DailyRollingFileAppender myAppender = new DailyRollingFileAppender(patternLayout, "TestOrig.log", "'.'yyyy-MM-dd-HH-mm");

您在控制台上看到任何错误吗?

错误的可能原因可能是,您尝试多次运行同一程序,而不结束先前启动的程序,这会导致文件访问权限问题。

I don't see any error here. I could see this is creating files when I tried for minutes.

DailyRollingFileAppender myAppender = new DailyRollingFileAppender(patternLayout, "TestOrig.log", "'.'yyyy-MM-dd-HH-mm");

Did you see any error on the console??

Possible reason of error for you could be , you are trying to run the same program multiple times, without ending the previously started program and that is resulting in file access permission issue.

太阳哥哥 2024-12-17 06:27:44

迈克,你上面的评论是正确的。除非在此期间有日志记录活动,否则您将不会获得新文件。如果您需要强制解决该问题,则需要使用可运行的线程启动一个线程,该线程在每个新小时开始后向日志中发布一行。

目标是从第 1 分钟开始,每 59.5 分钟在日志中发布一篇文章。

他的解决方案需要了解如何使用 Runnable 和 Thread 的基本标准知识。我假设您正在运行标准应用程序,而不是在托管服务器环境中

  1. 创建一个实现 Runnable 的类,
  2. 并使用 while 覆盖 run() 方法code> 循环到 true 布尔变量 (isAlive),当您的应用关闭时,您的应用可以将其设置为 false
  3. 在循环期间调用 static Logger logger = Logger.getLogger(YourClassName.class);.info("Logger Text") 方法,循环等待时间为 60分钟。
  4. 在应用程序启动时将 Runnable 放入 new Thread() 对象中,
  5. 在启动时将一个 info() 帖子发布到您的日志中。
  6. 当您启动应用程序时启动线程对象。

Runnable 的 run() 方法可以

public void run() { 
    while (isAlive) { // isAlive is a global-level (static, even) boolean 
                      // you declared earlier as true, your app should set it to false
                      // if your app decides to exit

        try { 
            logger.info("Rollover Log Text");
            Thread.currentThread().sleep(1000 * 60 * 60); // 60 minutes 
        } catch (InterruptedException ignore) { 
        }
    }
}

记住在启动 Thread 之前将 isAlive 设置为 true,将其设置为 false code> 关闭或错误/异常关闭时,并在设置为 false 后调用线程的 interrupt() 方法。这应该每小时记录一次。

Mike, you are correct in your comment above. You will not get a new file unless there is logging activity during that time. If you are required to force the issue, you'll need to start a thread with a runnable that posts a line to the log after the start of each new hour.

The goal is to make one post to your log every 59.5 minutes, starting from minute 1.

Basic standard knowledge of how to use Runnable and Thread are required for his solution. I am assuming you are running a standard application and not within a managed server environment

  1. create a class that implements Runnable
  2. overwrite the run() method with a while loop to a true boolean variable (isAlive) your app can set to false when your app shuts down.
  3. during the loop call the .info("Logger Text") method of a static Logger logger = Logger.getLogger(YourClassName.class); with a loop wait time of 60 minutes.
  4. Toss the Runnable into a new Thread() object at application start-up
  5. make one info() post to your log at startup.
  6. start the thread object when you start your app.

run() method of Runnable can be

public void run() { 
    while (isAlive) { // isAlive is a global-level (static, even) boolean 
                      // you declared earlier as true, your app should set it to false
                      // if your app decides to exit

        try { 
            logger.info("Rollover Log Text");
            Thread.currentThread().sleep(1000 * 60 * 60); // 60 minutes 
        } catch (InterruptedException ignore) { 
        }
    }
}

Remember to set isAlive to true before you start your Thread, set it to false on shutdown or error/exception close, and call the the interrupt() method of your thread after setting to false. This should log one time an hour.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文