简体   繁体   English

如何在项目级别配置log4j?

[英]How to configure log4j at project level?

I have a java project(note:- its not a web project).I am using log4j to log messages. 我有一个java项目(注意: - 它不是一个Web项目)。我正在使用log4j来记录消息。

Presently the steps I am following to do it are as follows: 目前我要遵循的步骤如下:

  • Created a log4j.properties file at project level. 在项目级别创建了log4j.properties文件。

  • Declared Logger logger = Logger.getLogger(MyClass.class); 声明Logger logger = Logger.getLogger(MyClass.class);

  • Then configured properties using -> PropertyConfigurator.configure("log4j.properties"); 然后使用 - > PropertyConfigurator.configure(“log4j.properties”)配置属性;

  • Then used logger.debug("message"); 然后使用logger.debug(“message”); to log my messages. 记录我的消息。

But the problem I felt with this approach is that I have to do the same in all the classes in my project ie from all the steps starting from declaring Logger logger . 但我觉得这种方法的问题是我必须在我的项目的所有类中执行相同的操作,即从声明Logger logger开始的所有步骤。

Is there any way so that I can configure my logger variable at a single place only once in my project and then just use the declared variable of logger to log the messages? 有没有办法让我可以在我的项目中只在一个地方配置我的记录器变量一次,然后只使用logger的声明变量来记录消息?

IMHO You should not have a common logger for normal logging purposes. 恕我直言你不应该有一个普通的记录器用于正常的记录目的。 Each class should create its own logger by Logger logger = Logger.getLogger(MyClass.class); 每个类都应该通过Logger logger = Logger.getLogger(MyClass.class);创建自己的Logger logger = Logger.getLogger(MyClass.class); . This might seem to be an overhead when you have few class files, but it will be better to follow this. 当你有很少的类文件时,这似乎是一个开销,但最好这样做。
By following this pattern of loggers you get the flexibility of controlling the level of logging at any level (whole application or any package or any class) at the configuration level(in log4j.properties). 通过遵循这种记录器模式,您可以灵活地在配置级别(在log4j.properties中)控制任何级别(整个应用程序或任何包或任何类)的日志记录级别。

You can give log4j.properties in your classpath and log4j will automataically pick it up. 您可以在类路径中提供log4j.properties ,log4j将自动获取它。
PropertyConfigurator.configure("log4j.properties"); is not required. 不需要。

Still if you want to do it, You can create your own logger class MyLogger with static methods for logging which will wrap the actual call to the logger. 如果你想这样做,你可以创建自己的记录器类MyLogger使用static方法进行记录,将实际调用包装到记录器。 Then from your individual classes you can call MyLogger.log() or MyLogger.debug() to log. 然后,从您的各个类中,您可以调用MyLogger.log()MyLogger.debug()来记录。

You can configure by the following way 您可以通过以下方式进行配置

# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM