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

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

问题描述

我决定在一个新的 Java 项目中使用 Log4J 日志框架.我想知道我应该使用什么策略来创建/管理 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 实例
  • 注意:这些文章已经在一定程度上考虑了这个问题:

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

    创建 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 是您要走的路.代码有时可能有点过分,但我不知道我被准确的上下文堆栈保存了多少次,该堆栈显示 Foo.bar() 是从 Y 层的应用程序 X 调用的.

    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天全站免登陆