【问题标题】:How to log a message from java.util.logging.Logger Logging and then print it to a text file?如何从 java.util.logging.Logger Logging 记录消息,然后将其打印到文本文件?
【发布时间】:2014-01-05 19:59:25
【问题描述】:

'logger.info(message);'我的代码中的行创建了这个输出:

2013 年 12 月 17 日下午 12:54:50 温室.GreenhouseControls$ControllerException

我想使用 PrintWriter 将该行打印到文本文件中。这是我到目前为止所拥有的:

public ControllerException(String message, int errorcode) {
          super(message);
          this.errorcode=errorcode;   

          Logger logger = Logger.getLogger(ControllerException.class.getName());
          logger.info(message);

          String fileName = "error.log"; 

          try {
            PrintWriter outputStream = new PrintWriter(fileName);
            outputStream.println("Time: " + ????);         // Not sure what to put here..
            outputStream.println("Reason: " + message);
            outputStream.close();
           } catch (FileNotFoundException e) {
            e.printStackTrace();
           }      
       }

我可以在打印行语句中包含什么来代替问号来实现这一点?

【问题讨论】:

  • 你想完成什么? outputStream.println("Reason: " + message); 行应该将Dec 17, 2013 12:54:50 PM greenhouse.GreenhouseControls$ControllerException 打印到您的文件中,这不会发生吗?你想为原因和时间部分显示什么??
  • @Ergin 我想我不需要两个打印语句。我可以在同一行打印“时间”和“原因”。我根本无法获得打印到文件的日期/时间。所以,我希望它在文件中打印 2013 年 12 月 17 日 12:54:50 PM温室.GreenhouseControls$ControllerException。

标签: java logging


【解决方案1】:

我会这样做:

public ControllerException(final String message, int errorcode) {
    super(message);
    this.errorcode=errorcode;

    Logger logger = Logger.getLogger(ControllerException.class.getName());

    logger.setFilter(new Filter() {
        @Override
        public boolean isLoggable(LogRecord record) {
            SimpleDateFormat sdf = new SimpleDateFormat("MMM dd',' yyyy HH:mm:ss a");
            String fileName = "error.log";

            try {
                PrintWriter outputStream = new PrintWriter(fileName);
                outputStream.println("Time: " + sdf.format(new Date(record.getMillis()))); 
                outputStream.println("Reason: " + message);
                outputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            return true;
        }
    });

    logger.info(message);
}

这样你就可以得到日志记录的确切日期。

【讨论】:

  • 我注意到你有 'super(message);'和'this.errorcode=errorcode;'在初稿中注释掉了,所以我删除了它们,我的程序运行良好。我应该再次包含它们吗?
  • @LooMeenin 你应该调用超级构造函数以便让它有机会正确初始化。
猜你喜欢
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
相关资源
最近更新 更多