简体   繁体   English

Java.util.logger继续写入新的日志文件

[英]Java.util.logger Keeps writing to a new log file

I'm having this issue where my logger keeps writing to a new file 我遇到了这个问题,我的记录器不断写入新文件

    Logger logger = Logger.getLogger("NewLogger");
    FileHandler fh;
    //create log file string 
    Date date = new Date(); 
    String yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd").format(date);
    String logFileName = "retrieveproductstracking_" + yyyyMMdd; 
    fh = new FileHandler("./" + logFileName + ".log");
    logger.addHandler(fh);
    SimpleFormatter formatter = new SimpleFormatter();
    fh.setFormatter(formatter);

    logger.setUseParentHandlers(false);
    logger.info(request.getRemoteAddr() + ", " + url + ", " + "timestamp" ); 

This code is being used in a JSP where it's called and the logger logs the URL, IP. 该代码正在JSP中使用,在该代码中调用它,并且记录器记录URL,IP。 The problem is that the logger writes to a new file every time, but not only that...it writes to all of the previous files before it too. 问题是记录器每次都写入一个新文件,但不仅如此……它还会写入所有先前的文件。

Not exactly what I had in mind for rotating logs. 旋转日志并不是我的初衷。

See image: http://puu.sh/cnu39/8b814e9f3f.png http://puu.sh/cnvKw/8c0e5dce11.png 查看图片: http : //puu.sh/cnu39/8b814e9f3f.png http://puu.sh/cnvKw/8c0e5dce11.png

You need to close the file handler with fh.close() once you've finished. 完成后,您需要使用fh.close()关闭文件处理程序。 Otherwise, you leave the files locked. 否则,您将文件锁定。 That's why your image is showing so many lock files open! 这就是为什么您的图像显示了这么多打开的锁定文件的原因!

指定第二个参数追加到现有文件。(以追加模式打开文件)

 fh = new FileHandler("logFileName.log",true); // true specify append mode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM