Why do we declare Loggers static final?

后端 未结 14 2016
陌清茗
陌清茗 2020-11-28 01:19

In Java, why is it best practice to declare a logger static final?

private static final Logger S_LOGGER
14条回答
  •  感情败类
    2020-11-28 01:40

    In addition to the reasons given in the other answers one thing I ran into was that if my logger was neither static nor final:

    ...
    public Logger logger = LoggerFactory.getLogger(DataSummary.class);
    
    public String toJson() {
      GsonBuilder gsonBuilder = new GsonBuilder();   
      return gsonBuilder.create().toJsonTree(this).toString();
    }
    ...
    

    in certain cases (when I was using the Gson library) I would get stackoverflow exception. My specific situation was to instantiate the class containing the non static non final logger. Then call the toJson method which invoked GsonBuilder:

    ...
    DataSummary ds = new DataSummary(data);    
    System.out.println(ds.toJson());
    ...
    

提交回复
热议问题