Log4J:创建Logger实例的策略 [英] Log4J: Strategies for creating Logger instances

查看:158
本文介绍了Log4J:创建Logger实例的策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定将Log4J日志框架用于新的Java项目。
我想知道我应该使用什么策略来创建/管理Logger实例以及为什么?

I decided to use Log4J logging framework for a new Java project. I am wondering what strategy should I use for creating/managing Logger instances and why?


  • Logger的一个实例每个类
    例如

  • one instance of Logger per class e.g.

class Foo {
    private static final Logger log = Logger.getLogger(Foo.class);
}


  • 每个线程一个Logger实例

  • 每个应用程序的一个Logger实例

  • 水平切片:应用程序的每一层中的一个Logger实例(例如视图层,控制器层和持久层)

  • 垂直切片:应用程序功能分区中的一个Logger实例

  • one instance of Logger per thread
  • one instance of Logger per application
  • horizontal slicing : one instance of Logger in each layer of an application (e.g. the view layer, the controller layer and the persistence layer)
  • vertical slicing : one instance of Logger within functional partitions of the application
  • 注意:此问题已被考虑在某些程度上这些文章:

    Note: This issue is already considered to some extent in these articles:

    创建Log4j记录器的开销是什么?

    Whats the overhead of creating a Log4j Logger

    推荐答案

    通常情况下,您需要设置记录器因为这是一个很好的逻辑组件。线程已经是日志消息的一部分(如果你的过滤器显示它们),那么切片记录器可能是多余的。

    Typically, you'd have loggers setup per class because that's a nice logical component. Threads are already part of the log messages (if your filter displays them) so slicing loggers that way is probably redundant.

    关于应用程序或基于层的记录器,问题是你必须找到一个坚持Logger对象的地方。不是什么大不了的事。更大的问题是某些类可能会在多个应用程序的多个级别使用...可能很难让您的记录器正确。或者至少是棘手的。

    Regarding application or layer based loggers, the problem is that you have to find a place to stick that Logger object. Not a really big deal. The bigger issue is that some classes may be used at multiple levels of from multiple applications... it could be difficult to get your logger right. Or at least tricky.

    ...你想要的最后一件事是你的日志设置中的错误假设。

    ...and the last thing you want is bad assumptions in your logging setup.

    如果您关心应用程序和图层并且具有易于分离的点,那么NDC就是您的选择。代码有时可能有点过分,但我不知道有多少次我被一个准确的上下文堆栈保存,显示我从层Y中的应用程序X调用了Foo.bar()。

    If you care about applications and layers and have easy separation points, the NDC is the way to go. The code can be a little excessive sometimes but I don't know how many times I've been saved by an accurate context stack showing me that Foo.bar() was called from application X in layer Y.

    这篇关于Log4J:创建Logger实例的策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆