Reputation: 1740
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:
Created a log4j.properties file at project level.
Declared Logger logger = Logger.getLogger(MyClass.class);
Then configured properties using -> PropertyConfigurator.configure("log4j.properties");
Then used 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 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
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
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