Loggable: a simple log4j meta-library – Part 1

If you work in a J2EE environment, you surely have (or at least will have) used the standard Apache log4j library almost once. This powerful and configurable logging library is commonly used throughout whole enterprise projects, for many reasons: debugging, testing, exception logging, tracing, application profiling, et cetera.

A common code that shows how to use a org.apache.log4j.Logger instance is the following:

[sourcecode language=”java” highlight=”6,9″][RAW]
package com.marzapower.test;

import org.apache.log4j.Logger;

public class MyClass {
private static final Logger logger = Logger.getLogger(MyClass.class);

public static void main(String… args) {
logger.debug("Hello World!");
}
}
[/RAW][/sourcecode]

As you can see, you define a private (visible only to the instances of this specific class) static (shared amongst all instances of the class) final (constant, not variable) Logger instance, and then you use it within the class. If you had another class, you should define a similar object into that class too. If you had a third, again, you’d define a Logger in that class too. And so on.

But when the number of the classes in your project grows, this approach easily becomes very frustrating. You are writing your code, and want to use a Logger, but you cannot do it directly unless you define the Logger instance for your classes. Again, if you are refactoring an existing class, that heavily uses the Logger instance for debugging purposes, and you delete all the Logger.debug() calls then … the classic yellow exclamation mark flag appears in your Eclipse editor: the private Logger instance defined is not being used anymore, so its declaration should be removed. And so on, you probably have faced a different (but still similar) problem before.

A solution: use Java Annotations and a centralized controller

Well, I have read this interesting article written by a friend of mine, and an ex-colleague too, and have thought to myself: “Is there a way to avoid this declaration overhead, and use a Logger instance freely throughout my whole application, demanding its creation and handling to a centralized controller? Wouldn’t it be useful using Java Annotations to drive such logic?”.

The answer is: “Yes!”. And I’ll show you how to do this.

The goal

I followed this base architecture: every class in your application will call a centralized controller to retrieve a suitable org.apache.log4j.Logger instance. This instance will be created and returned depending on the parameters of the class set by a custom annotation.

The centralized controller will be my com.marzapower.loggable.Log class. The annotation will be my com.marzapower.loggable.Loggable annotation. Using these two elements in conjunction within a class of our application, we will no longer need to define a private Logger instance. The @Loggable annotation will drive the logic, and the public static method Log.get() will be our common interface to the log4j world.

(I thought it would have been nice to call the method ger() instead of get(), just to write Log.ger(), but that’s not a good name for that method …)

We could rewrite our first example this way:

[java highlight=”5, 8″][RAW]
package com.marzapower.test;

import com.marzapower.loggable.*;

@Loggable
public class MyNewClass {
public static void main(String… args) {
Log.get().debug("Hello World!");
}
}
[/RAW][/java]

Isn’t it more concise and clear?

The @Loggable annotation

But, how can we drive the Log controller logic in order to return the correct Logger instance for our class? We use the @Loggable annotation for this. The @Loggable annotation, if present, must be set before the class definition. The annotation is defined this way:

[java][RAW]
package com.marzapower.loggable;

import java.lang.annotation.*;

@Documented
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
public @interface Loggable {
String loggerName default "";
Class clazz() default Object.class;
boolean exclude() default false;
LogLevel logLevel() default LogLevel.DEBUG;

public enum LogLevel {
TRACE, DEBUG, INFO, WARN, ERROR, FATAL
}
}
[/RAW][/java]

Let’s look at the parameters:

  • loggerName: the name of a logger defined in the log4j configuration for the project. It is optional, and the default value is an empty string
  • clazz: is an instance of Class<?> and will represent the object passed to the Logger.getLogger(Class<?>) constructor. It is optional, and the default value will be Object.class
  • exclude: a boolean parameter that determines wether the class should effectively log or not, its default is false
  • level: a LogLevel instance that defines the custom log level for the class, its default is LogLevel.DEBUG

First of all, to enable logging for a specific class we have to do nothing. Just from the beginning, every single class will be capable of logging with no additional effort (= no additional declarations); you will never need the recurring “bla bla bla Logger.getLogger(bla bla bla)” overhead. In fact, if no @Loggable annotation is set, the Log.get() method will return the root logger of log4j to the caller class.

Some usage examples

If you want to enable the logging capabilities of your class, using its standard log4j Logger instance, you should use:

[java][RAW]
@Loggable
class GenericClass {

}
[/RAW][/java]

In this example, Log.get() will return the same object as Logger.getLogger(GenericClass.class). Also, if you would disable the logging capabilities of a class that uses Log.get() for logging, you could use the following:

[java][RAW]
@Loggable(exclude = true)
class SilentClass {

}
[/RAW][/java]

Declaring SilentClass this way, every call to the Log.get() method will return a silent logger (eg. with log level set to “OFF”). Now, imagine that you want to use, for your class, a Logger instance different from the standard one. In the classic log4j approach you’d do this:

[java][RAW]
class ThisClass {
private static final Logger logger = Logger.getLogger(AnotherClass.class);

}
[/RAW][/java]

while now you can do it in a simpler form:

[java][RAW]
@Loggable(clazz = AnotherClass.class)
class ThatClass {

}
[/RAW][/java]

(Update) You can do the same, if you want to use a specific log4j named logger instead of the standard one. You just will have to change the latest example this way:

[java][RAW]
@Loggable(loggerName = "verboseLogger")
class VerboseClass {

}
[/RAW][/java]

Also, you could have the need of limiting all the logger calls of a class to a WARN level, or higher, but the current log4j configuration for that class has a larger INFO level. You can force this need through the @Loggable annotation. Eg.:

[sourcecode language=”java”][RAW]
@Loggable(level = LogLevel.WARN)
class WarnerClass {

}[/RAW][/sourcecode]

From now on, the WarnerClass will log only messages with level WARN or higher, despite of the actual log4j default configuration.

Next episode: the controller

As we have seen, the @Loggable annotation is really helpful. But, it will have no effect without its back-end class, the centralized controller Log. I will describe you this class in one of my next posts, and I hope to release a fully commented and tested library soon.

If you have questions/suggestions for this meta-library, please drop me a line. Keep in touch!

Update: the second “episode” is now available.
Also, the definition of the @Loggable annotation has been revised introducing the “loggerName” parameter

4.489 thoughts on “Loggable: a simple log4j meta-library – Part 1

  1. What i don’t realize is actually how you’re no longer
    really much more smartly-preferred than you
    might be right now. You are very intelligent.
    You recognize thus considerably relating to this subject, made me for my part
    believe it from numerous varied angles. Its like men and women aren’t interested unless it’s something to do
    with Lady gaga! Your individual stuffs nice.

    At all times handle it up!

  2. Some flowers have more potent aromas as opposed to runners, so that you probably would not
    want something such as a star gazer lily since they
    may affect a mid-sized area quickly. When selecting your cover for your business, it is important to recall the
    compulsory components such as goods in transit, which suggests if something happened
    in your delivery during transit, you happen to
    be covered and you will be reimbursed for the loss. An agency often connotes several agents
    working inside same organization, often with additional staffing and resources.

  3. With this, TESOL instructors look to exciting
    professions and employment contracts that could positively change careers and even personal
    lives. Furthermore, such preparation materials offer sufficient possibility to the
    applicants to guage regarding their skills by just themselves, so they really
    exactly know whereby they have to place more efforts.
    In the stressful life people currently live when you find yourself
    trying to study then afternoon classes is probably not a
    viable choice.

  4. Many certification providers have implemented NDAs to stop examinees from stealing their
    information and creating in mass. Different tracks across these levels align with your task
    role or industry. Another method of getting an affordable computer laptop is always to wait for
    technology to advance.

  5. In some companies, they offer the berry products in kinds of instant drink powders,
    juice, and smoothies. The Yellow parrot can be a generic term to the Yellow Naped Amazon, Yellow Crowned Amazon as well as the Yellow Headed Amazon parrot or Double Yellow Headed Amazon as well as the Magma Double Headed Amazon. Make sure to drop by the countless street vendors
    that will provide you with anything and everything,
    from quivers and arrows, to blowpipes and piranha tooth-made necklaces.

  6. My strength, flexibility, mobility of my joints, neurological fitness (learning
    new skill sets), balance, portability (no machines needed), and body recovery has been significantly improved.

    When you’re just about to pick a machine, check if you simply can’t try to perform the same exercise with dumbells instead.
    Fiber is essential and quite often overlooked by those who check labels for protein.

  7. Finally shooting games were highly encouraged by different
    sport associations. These free online games is going to take us to a separate virtual world itself so you can’t say for sure we kill time without our knowledge.
    Playing this game will be a huge pleasure to all or any the gaming freaks due to its excellent grip on storyline, magnificent gaming environment and incredible graphic detail from alien jungles to harsh arctic vistas.

  8. That’s still less capacity as opposed to onboard storage of other tablets,
    and not quite definitely convenience of digital media.
    Yes, but you can’t adjust the font, so PDFs aren’t as reader-friendly as mobi files.

    They were launched on the web across the same date about
    many years ago and also have been fighting since for the market monopoly.

  9. plenty of hair at the same time) or possibly a slanted tip (will give
    you the very best control). Whether it is a designer pencil or not, there is a lot of money spent on makeup every year and what if you could eliminate this
    cost from your expenses all together. They are taking
    advantage in the many perks that cosmetic tattooing lets you have,
    including not waste time, saving cash, looking beautiful and overall having the
    capacity to get up and not apply plenty of makeup.

  10. The very first thing you need to do is check cosmetic plastic surgery clinics near your geographical area
    to ascertain if they could provide you with cosmetic tattooing.
    Ladies that have very oily skin may benefit because the constitute is just
    not affected by oily skin. It is vital to hold some things at heart
    prior to deciding to actually choose cosmetic tattooing for corrective or permanent make-up requirements.

  11. This is a path breaking method, much appreciated
    to the ink extraction technique which it uses.
    Normally, there’s a big book brimming with pictures in the work they
    have got recently performed. It is important to maintain some things in mind before you actually choose cosmetic tattooing for corrective or permanent make-up requirements.

  12. If you are planning an Amazon campaign for
    the book launch, you will require assistance
    from a fantastic network of non-public and professional
    friends to help you. With the internet connectivity that comes free of charge while using Kindle2 it
    is simple to download stuff and focus with great joy. Sign into your Kindle Direct Publishing account out of your homepage at
    .

  13. Rowling’s decision to promote Harry Potter e – Books through Google’s online
    bookstore. The Yellow parrot is a generic term to the
    Yellow Naped Amazon, Yellow Crowned Amazon and also the Yellow Headed
    Amazon parrot or perhaps the Double Yellow Headed Amazon and the Magma Double Headed Amazon. Sign in your Kindle Direct Publishing account out of your
    homepage at .

  14. You can start receiving the quotes from all the insurers using the Internet.
    When selecting your pay for your business, you should remember
    the compulsory components such as goods while in cargo, which suggests if something happened
    in your delivery during transit, you might be covered and will be reimbursed for the loss.

    Examples of individual insurance companies that provide cheap auto quotes
    online are Nationwide Mutual, Progressive, Esurance,
    and Geico.

  15. Get their opinion on their own experience if that they had
    great results obtain the naming of their professional. Here, we’ll discuss tattooing your eyebrow and several other makeup techniques which might be
    becoming quite popular with this day and age. It is crucial to hold some things planned
    before you actually choose cosmetic tattooing for corrective or permanent make-up requirements.

  16. So if you need to find cheap cab insurance you will need to start from building a report on things what you are
    looking for your insurance coverage to cover. Paying a coverage for the car
    is a necessity, it’s not at all a luxury, as driving
    without car insurance is completely prohibited.

    Pay in full-If you can pay for the entire duration of the policy
    upfront they can give you automobile insurance without any credit check.

  17. Hello! I could have sworn I’ve been to this blog before but
    after browsing through some of the post I realized it’s new to me.
    Anyhow, I’m definitely delighted I found it and I’ll be book-marking and checking back frequently!

  18. On paper, the Kindle DX looks impressively feature packed, but could
    it replace the nice old book. Kindle’s screen is the foremost mainly because it doesn’t heat
    up and it has no back light thus it is non-glaring. They were launched online round
    the same date about fifteen years ago and have been fighting since for the
    market monopoly.

  19. This is a path breaking method, much appreciated to the
    ink extraction technique which it uses. Ladies who have very oily skin will benefit because the make-up is not suffering from oily skin. Three dimensional hair simulation techniques can provide the look off
    hair growth for the people with patchy growth of hair.

  20. Accentuated looks, fine features, perfect physic and precisely what never loses charm despite a quick
    paced lifestyle is one thing that each one folks wants,
    and in fact who doesn’t need to appear enchantingly attractive.
    Whether it is a designer pencil or not, you will find there’s lot of cash spent
    on makeup each and every year and let’s say you might eliminate this cost from a expenses all together.
    Three dimensional hair simulation techniques can give each side hair
    growth for anyone with patchy growth of hair.

  21. Push ups – Push ups are another chest muscles exercise that can be done in your own home without any
    equipment at all. Walking and Aerobic:Adapt some light exercise which will help you to maintain good health.
    Depending on the body type you may need a different type of workout and
    different diet.

  22. Due to the massive costs of potential issues that occur on-site of
    the job, the premium that is associated with insurance protection is far less expensive.
    After all, if an item is damaged or stolen and isn’t covered you may not be covered.

    That it takes years to acquire a professional
    qualification sometimes more time to establish one’s reputation and credibility being
    a consulting professional.

  23. But a major addition that lots of are over looking may
    be the power to download software with the web store
    Dsi. There is plenty of action while you proceed from the levels
    causing mayhem. Playing farmville might be a huge pleasure to any or all
    the gaming freaks due to its excellent grip on storyline, magnificent gaming environment and incredible
    graphic detail from alien jungles to harsh arctic vistas.

  24. This is a path breaking method, much appreciated
    for the ink extraction technique it uses. This is the reason your artist not merely must be educated inside the medical sense too.

    They are taking advantage of the many perks that cosmetic tattooing enables you
    to have, including time savings, conserving money, looking beautiful and overall with the ability to wake and not apply plenty of makeup.

  25. Rowling’s decision to showcase Harry Potter e – Books through Google’s online bookstore.
    The commission for Amazon products starts at 4% and increases with the
    quantity of monthly sales. ) To do it right, you need to do should spend some money, but it is a thing that
    is at take most suitable people.

  26. In particular, the Inca Trail and Machu Picchu are making Peru the most popular
    countries to go to in South America. With the internet connectivity that comes totally
    free with the Kindle2 you can easily download stuff and focus with great
    joy. They were launched on the web around the same date about fifteen years ago and possess
    been fighting since to the market monopoly.

  27. In particular, the Inca Trail and Machu Picchu are making Peru just about the most popular
    countries to visit in South America. Yes, however you can’t adjust the
    font, so PDFs aren’t as reader-friendly as mobi files.
    Their markings and attractive colors is partly what offers them their popularity.

  28. Online bingo is probably the coolest location to constantly hunt for those best bingo that have delicious welcome bonuses
    where the players can find many ample games which could offer them tremendous entertainment.
    Staying alive for duration will truly provde the defining edge and that’s only possible when you know the maps as well as
    the weapons with the COD Black Ops 2. Have a bird eye on all bingo sites that’s lavishly offering to its players
    100% to 750% first deposit bonus and you can subscribe the site
    with 5 to 25 free no deposit required.

  29. That’s still less capacity compared to onboard storage of other tablets, and not quite definitely convenience of digital media.

    Kindle’s screen is the better mainly because it won’t warm up and has no back light thus it is
    non-glaring. They were launched on the web round
    the same date about fifteen years ago and still have been fighting since for that market monopoly.

  30. When seeking your artist try to find others which may have had
    the method done. Normally, you will find there’s big book full of
    pictures with the work they have got recently performed.
    Thanks to some highly skilled permanent constitute artists it’s now accessible to everyone.

  31. loads of hair concurrently) or even a slanted tip (will give you the very best control).
    Normally, there is a big book full of pictures with the work they have recently performed.
    A true professional can have a portfolio and wont be offended at all should
    you request to look at it.

  32. You can start obtaining the quotes all the insurers
    via the Internet. After all, automobile item is damaged or stolen and isn’t covered you
    possibly will not be covered. Examples of
    human insurance firms that provide cheap auto quotes
    online are Nationwide Mutual, Progressive, Esurance, and Geico.

  33. This is a path breaking method, much appreciated for
    that ink extraction technique that it uses. Rejuvi tattoo removal is not only a highly effective process but can be non-intrusive, painless
    and safe. A true professional could have a portfolio and wont be offended at all in the event you request to consider it.

  34. Hello would you mind stating which blog platform you’re using?

    I’m planning to start my own blog in the near future but
    I’m having a tough time selecting between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems different then most blogs and I’m
    looking for something completely unique.
    P.S Sorry for getting off-topic but I had to ask!

  35. Purchase a building having a sprinkler system and
    purchase a central station fire and burglar alarm. Paying an insurance coverage on your car is a necessity, it’s not an extravagance, as driving without car
    insurance is very prohibited. That it takes years to acquire a professional qualification and
    many more time and energy to establish one’s reputation and credibility
    like a consulting professional.

  36. But a major addition that lots of are gone looking could be
    the power to download software from the online shop Dsi.
    There is a good amount of action as you proceed over the
    levels causing mayhem. Multiple people have tried locating a way to
    do this online, simply to be disappointed through the information they receive in forums
    and forums no longer working, or worse, destroying their game or system.

  37. But a significant addition that lots of are gone looking will be
    the power to download software over the web store Dsi. These
    free online games will need us to a separate virtual world itself and you can’t say for sure we kill time without our knowledge.
    Playing this game might be a huge pleasure to everyone the gaming freaks
    because of its excellent grip on storyline, magnificent gaming environment
    and incredible graphic detail from alien jungles to harsh arctic vistas.

  38. Finally shooting games were highly encouraged by different sport associations.
    Although the graphics are fantastic and the game engine
    is smooth and responsive, there aren’t any real
    new elements combined with the sport. Multiple folks have tried getting a method this
    online, simply to be disappointed with the information they receive
    in forums and boards bust, or worse, destroying their game
    or system.

Lascia un commento

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