Abhinav
Abhinav

Reputation: 1740

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.

Presently the steps I am following to do it are as follows:

But the problem I felt with this approach is that I have to do the same in all the classes in my project i.e. from all the steps starting from declaring 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?

Upvotes: 4

Views: 2922

Answers (2)

basiljames
basiljames

Reputation: 4847

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);. 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).

You can give log4j.properties in your classpath and log4j will automataically pick it up.
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. Then from your individual classes you can call MyLogger.log() or MyLogger.debug() to log.

Upvotes: 4

John Smith
John Smith

Reputation: 3

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

Upvotes: 0

Related Questions