Loggable: a simple log4j meta-library – Part 2

In a recent post I described the goal of my Loggable meta-library. If you haven’t read it yet, I suggest you to do it now.

What we are going to do now is analysing the second main component of the meta-library, the centralized controller Log.

How does it work

The main responsibility of the Log class is handling the logic behind the creation and returning of the Logger instance that the caller class should use. This logic, as we’ve already seen, is driven by the @Loggable annotation.

The Log class will have a single point of access: the public static method get(). Let’s look at if, briefly:

[java highlight=”9″][RAW]
public static Logger get() {
// Retrieve the StacKTraceElement of the caller method
StackTraceElement caller = getCaller();
// Retrieve the caller class
Class<?> clazz = getClass(caller);
// and its Loggable annotation instance
Loggable annotation = getAnnotation(clazz);

logger.debug("Returning a Logger for " + clazz.getSimpleName());

// Retrieve the suitable logger for the caller class and returns it
Logger suitableLogger = getLogger(annotation, clazz);
return suitableLogger;

This method does a precise series of things:

  1. Retrieves the stack trace element related to the caller method
  2. Retrieves the Class<?> instance which describes the caller class
  3. Reads the @Loggable annotation from the caller class
  4. Returns the suitable Logger instance, depending on the class and its @Loggable annotation definition

The whole code for this class will be available within the meta-library package, so I’ll focus just on the main private method: getLogger().

Bonus hint: as you can see, in my development environment the Log class makes a direct access to a Logger instance. This is strictly necessary because of recursions problems: if the Log class would call itself for logging purposes, this will generate a never-ending recursion stack. Try it, and try to explain why: this will be your homework for today 🙂 .

The private getLogger() method

This method is the key for everything, I’d say. It controls the logic and the interpretation of the annotation parameters. It handles the Logger instance creation and retrieval and will be in our scope in the next paragraphs. The source code is the following:

private static Logger getLogger(Loggable annotation, Class<?> clazz) {
if (annotation == null)
return LoggerContainer.getRootLogger();

if (annotation.exclude())
return LoggerContainer.getVoidLogger();

// If a "loggerName" parameter has been passed to the annotation,
// returns that specific logger instance
if (!"".equals(annotation.loggerName()))
return LoggerContainer.getInstance(annotation.loggerName(), annotation);

// If no "class" parameter has been passed to the annotation, returns
// the default logger for the caller class …
if (annotation.clazz() == Object.class)
return LoggerContainer.getInstance(clazz, annotation);

// … otherwise use the "class" parameter to build the logger
return LoggerContainer.getInstance(annotation.clazz(), annotation);

What does it do? Just what we said in the previous “episode”:

  1. If no @Loggable annotation has been set for the class, returns the root logger
  2. If the annotation requires the class to be excluded by logging, returns a void logger
  3. If the annotation defines a logger name, returns that logger (= Logger.getLogger(annotation.loggerName()) )
  4. If the clazz parameter of the annotation is still the default (Object.class), returns the default logger for the caller class (= Logger.getLogger(CallerClass.class) )
  5. Otherwise, returns the default logger with the class specified in the annotation (= Logger.getLogger(annotation.clazz()) )

How does this work? This method uses a third class, LoggerContainer. This is a really simple container: when a logger is required, if it has already been built and customized, the same object will be returned; otherwise, the new instance is built, customized, added to the local container and finally returned. This will save time and memory when we call the Log.get() method. (It is a somewhat similar implementation of the static final definition for the usual logger instance).


Given these three simple components, two classes and a single annotation, I tried to build a handy log4j meta-library. I am currently using it in a bunch of personal projects as it has drastically simplified the logging process throughout the whole applications. I found it very helpful and customizable.

I still need some feedback on this project. I will try to complete the setup of the package, and hope to release version 1.0 of the meta-library as soon as possible.

See you soon!

Update: the first official release is now available! Give it a try!

1.752 thoughts on “Loggable: a simple log4j meta-library – Part 2

  1. Thank you so much for giving everyone remarkably terrific chance to read critical reviews from this blog. It’s usually very cool and also packed with a great time for me and my office co-workers to visit the blog more than 3 times per week to read the fresh issues you will have. And definitely, we are at all times satisfied with your tremendous tactics served by you. Selected two areas in this posting are rather the best I’ve had.

  2. I am only commenting to let you be aware of what a superb discovery my cousin’s girl went through visiting your site. She discovered plenty of pieces, which include what it is like to have a marvelous helping nature to get other individuals quite simply know just exactly a number of multifaceted subject matter. You truly surpassed our expected results. Many thanks for imparting such valuable, healthy, educational and also easy thoughts on your topic to Tanya.

  3. Howdy! This is my 1st comment here so I just wanted to give a quick shout out
    and tell you I genuinely enjoy reading your posts. Can you suggest any other blogs/websites/forums that deal with the same subjects?

  4. I loved as much as you will receive carried out right here.
    The sketch is attractive, your authored subject matter stylish.

    nonetheless, you command get got an impatience over that you wish be delivering the following.
    unwell unquestionably come more formerly again as exactly the same
    nearly a lot often inside case you shield this hike.

  5. Thanks for your write-up. I also believe laptop computers are becoming more and more popular today, and now are usually the only sort of computer employed in a household. Simply because at the same time actually becoming more and more reasonably priced, their computing power is growing to the point where they are as highly effective as desktop computers coming from just a few in years past.

  6. Thanks for expressing your ideas. The one thing is that individuals have a selection between government student loan along with a private student loan where it is easier to decide on student loan debt consolidation than through the federal student loan.

  7. Excellent blog! Have you got any hints for aspiring writers?
    I’m hoping to get started on my site soon but I’m a little bit
    lost on everything. Can you advise beginning from a totally
    free platform like WordPress or take a paid option? There are plenty of choices around that I’m completely confused ..
    Any ideas? Many thanks!

    Feel free to surf to my page … NitaUDelva

  8. Undeniably believe that that you simply stated.
    Your preferred justification appeared to be about the
    web the easiest thing to be familiar with. I have
    faith that to you personally, I definitely get irked while people take into
    consideration worries that they just do not know about. You been able to
    hit the nail upon the top and defined out the whole thing without needing
    side-effects , people can go on a signal. Will likely be
    back to obtain more. Thanks

    Stop by my homepage … 6 ring planner with zipper

  9. I have noticed that online diploma is getting well-liked because attaining your college degree online has become a popular choice for many people. A lot of people have definitely not had an opportunity to attend a normal college or university however seek the increased earning potential and career advancement that a Bachelors Degree gives you. Still others might have a diploma in one training but wish to pursue something they already have an interest in.

  10. You can certainly see your expertise in the work you write. The world hopes for even more passionate writers such as you who aren’t afraid to mention how they believe. All the time go after your heart.

  11. Hi there just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Safari. I’m not sure if this is a format issue or something to do with internet browser compatibility but I figured I’d post to let you know. The design and style look great though! Hope you get the problem resolved soon. Cheers

  12. Undeniably think that which you stated. Your best reason appeared to be around the web the easiest
    thing to be aware of. I believe that for you, I certainly get annoyed while people consider
    worries that they just tend not to understand about.
    You been able to hit the nail upon the top plus defined out everything without the need of side-effects , people could take a signal.

    Will likely come back to obtain additional. Thanks

    My web blog; bullet journal dotted grid notebook

  13. I precisely needed to thank you so much once more. I am not sure what I would’ve handled without the entire points shown by you about that field. This was a terrifying problem in my opinion, nevertheless taking note of the expert technique you managed the issue took me to jump with delight. I’m happy for this service and even expect you find out what a great job you’re accomplishing teaching the others by way of your blog post. I’m certain you’ve never got to know all of us.

  14. I would like to show my appreciation for your kindness in support of those people who should have assistance with your area of interest. Your real commitment to passing the solution across turned out to be really helpful and have surely allowed associates like me to reach their targets. Your new warm and friendly tips and hints means a great deal to me and much more to my fellow workers. Regards; from everyone of us.

  15. I have to get across my respect for your generosity in support of men and women who actually need help on that field. Your special commitment to getting the message all over had been certainly valuable and have consistently encouraged girls just like me to arrive at their ambitions. This valuable useful information indicates much a person like me and extremely more to my mates. Regards; from each one of us.

  16. I intended to create you this very small observation to say thank you once again for all the magnificent knowledge you’ve provided on this page. It is quite unbelievably open-handed of you to grant unreservedly what a lot of folks could possibly have advertised as an ebook in making some dough for their own end, particularly given that you might have tried it in case you desired. Those guidelines likewise worked to become good way to realize that other individuals have a similar dreams just like mine to know the truth great deal more in respect of this condition. I’m sure there are numerous more pleasant opportunities ahead for those who find out your site.

  17. I needed to compose you that little bit of note to be able to give many thanks over again just for the incredible ideas you have featured here. This has been extremely open-handed with people like you to offer openly precisely what a few people would have sold for an ebook in making some profit on their own, primarily considering that you could possibly have done it if you decided. These inspiring ideas likewise served to become good way to be sure that most people have similar dreams like my very own to learn good deal more with regard to this issue. I’m sure there are several more fun opportunities up front for those who scan through your blog.

  18. I have been browsing online more than 3 hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. Personally, if all website owners and bloggers made good content as you did, the web will be a lot more useful than ever before.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *