Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to create a logger instance for every class?

I am now using static method to log (because I find it very easy to log in Android), but now I need to configure different appenders for different classes, so I have a problem with static logging method.

And I read Log4J: Strategies for creating Logger instances, I notice it is time for me to change the logging strategy, so I will need the following code to my class which needs a special logger.

private static final Logger logger  =  Logger.getLogger(XXXX.class);

I feel since this is repeated job, so is there any ways for us to avoid adding repeated code to every single class, or just write less code. Will AOP or dependency injection can do such jobs?

I am using log4j and Spring, but any other ways to do that will be highly appreciated.

like image 359
JaskeyLam Avatar asked Nov 20 '14 11:11

JaskeyLam


People also ask

What is a logger class in Java?

A Logger class is used to create a logger object which is used to log messages. A logger object is provided with a name and has a set of methods which are used to log messages at the different levels.

How to use customized class for logging?

We can use the customized class with any handlers. If you are using Logging frameworks, you can use other layouts such as HTML, JSON, Syslog, plain text, etc. It shows the rough guide to the importance and urgency of the log message, and also controls the logging details. Each log level object has an integer value.

Should I have static loggers for my classes?

Just a note, for log4j at least, if you are using the class name as the look up then it will be the same logger instance every time. No reason to grab it again and again for each class instance. You might as well keep it statically. There are pros and cons for having static loggers.

What is the use of createlogger() method?

It acts as a wrapper for all the logger providers registered to it and a logger it creates can write to all the logger providers at once. As we can see, it has two methods, the CreateLogger () method, and the AddProvider () method. As the name suggests, the CreateLogger () method is responsible for creating a new logger instance.


1 Answers

You can try with Lombok project. You just have to add lombok library into your classpath and ofcourse you need log4j libraries too. and use @Slf4j annotation in class level, then you should be able to write log messages like this. log.info("message") without creating static logger instance.

more on here http://projectlombok.org/features/Log.html

like image 92
Lovababu Avatar answered Sep 28 '22 03:09

Lovababu