[向类中的记录器添加文件处理程序时在哪里处理IOException?

问题描述 投票:0回答:1

我正在尝试为我的应用程序设置日志记录系统。

我已经看到here,可以将日志发送到单个文件。代码如下:

package com.javacodegeeks.snippets.core;

import java.util.logging.FileHandler;
import java.util.logging.Logger;

public class WriteLogEntriesToLogFile {

    public static void main(String[] args) throws Exception {

        boolean append = true;
        FileHandler handler = new FileHandler("default.log", append);

        Logger logger = Logger.getLogger("com.javacodegeeks.snippets.core");
        logger.addHandler(handler);

        logger.severe("severe message");

        logger.warning("warning message");

        logger.info("info message");

        logger.config("config message");

        logger.fine("fine message");

        logger.finer("finer message");

        logger.finest("finest message");

    }

}

就我而言,我想将此日志添加到类中。我附加了一个基本类和我尝试过的内容(该类是单例,因此该事实包括在示例中):

public class MyClass {

    FileHandler handler = new FileHandler("MyClass.log", false);
    Logger logger = Logger.getLogger(MyClass.class.getName());

    // SINGLETON PATTERN
    private static final MyClass SINGLE_INSTANCE = new MyClass();         
    private MyClass() {
    }
    public static MyClass getInstance() {
      return SINGLE_INSTANCE;
    }    

    public void doStuff() {

        Logger.getLogger(MyClass.class.getName()).log(Level.FINE, "Log Text");

    }

}

但是我得到:

  1. FileHandler handler = new FileHandler("OrderFlowDrawer.log", false);中:未报告的IOException。
  2. Logger logger = Logger.getLogger(MyClass.class.getName());中:记录器声明应为静态且最终的。

据此,我有以下我无法完全理解的问题/疑问:

  1. 我应如何处理IOException?
  2. 为什么记录器声明应该是静态的和最终的?

[我正在使用Java 8以防可能。

java logging
1个回答
1
投票

我应如何处理IOException?

这是一个很好的问题,答案很多。我经常仍然使用System.err.println(...)报告此类问题。特别是在日志记录子系统,配置或其他启动操作失败的初始化问题。这意味着当我运行应用程序时,仍然存在某种console.log。这也可以捕获由行为不佳的第三方软件发送到stderr的罕见JVM错误或消息。

这意味着,如果由于某种引导问题而导致应用程序快速失败,我将继续查看console.log,以查看是否存在任何信息。这也意味着我应该向"System is running"发出console.log类型的消息,以便在出现问题时知道何时切换到查看日志文件而不是控制台。

如果Logger构造函数抛出IOException,则对于static字段,我将异常捕获为RuntimeException并重新抛出。类似于:

private static final Logger;

// this static black is executed before the class constructor and is the way
// that I initialize static fields that throw exceptions
static {
   try {
      logger = Logger.getLogger(MyClass.class.getName());
   } catch (IOExcepion ioe) {
      System.err.println("Initialization of logger threw");
      ioe.printStackTrace();
      // this will cause the class to not initialize and typically brings down the JVM
      throw new RuntimeException("Initialization of logger threw", ioe);
   }
}

为什么记录器声明应该是静态的和最终的?

static字段在一个类的多个实例之间共享。通常,如果您有多个MyClass实例,则它们应该共享记录器的同一实例,而每个类实例都没有一个。就是说,偶尔我[[do想要一个每个类实例的记录器,因为我想分隔记录前缀,但这很少见。

final可能很重要,这取决于记录程序的实现方式,就确保在线程线程共享之前将记录类完全使用之前,将其完全初始化。 final字段必须完全构建,并且编译器无法延迟其初始化。鉴于记录器可能被多个线程使用,这一点很重要。 final还可以确保某些行为不当的代码不会更改记录器的值或将其设置为null。类的不同部分将依赖具有值的logger字段,并且不想在任何地方都使用if (logger != null) ...类型模式。
© www.soinside.com 2019 - 2024. All rights reserved.