ferbolg
ferbolg

Reputation: 1557

How to add logging efficiently into a Java web-project?

I'am creating a quite simple JSP/Servlets web project with MVC architecture.

I have a prerequisite to add logging with log4j to the project. As I haven't been implementing logging using Log4j before, I'd like to hear some tips about how to implement it in an efficient way.

The main concern is how to share objects responsible for logging throughout the project without creating a new one each time I want to write another message.
And what about file structure and message organization, is it better to write info about date based operation and user-action in separate files or in one file?

Maybe it sounds odd, but I'd like to hear comments from people who have experience on this, since I am a newbee :)

Thanks to everybody in advance!

Upvotes: 2

Views: 878

Answers (1)

Ray Toal
Ray Toal

Reputation: 88378

In log4j, you will need a logger object for each category, not for every single object. Since in general your controllers, services, daos and the like are often singletons, including a logger object as an instance variable in each is okay. You will write something like

public void MyServiceImpl implements MyService {
    private Logger logger = Logger.getLogger(getClass());

    ....
}

If you have a bunch of controllers that all need their own logger (and ditto for services and daos), you can even put that Logger declaration in an abstract base controller (ditto for services and daos). It can be a protected field, or private with a getter, but because the logging category is important, you will need a logger for each controller (sub)class.

Of course, having too many loggers is a valid concern, so if your classes are not singletons, you need to do something else. If you are going to add logging to domain objects, for which dozens or hundreds are created, you do not want to create a logger object for each domain object. In this case, I have used (and seen others use) loggers as class variables, for example:

public void MyDomainObject {
    private static Logger logger = Logger.getLogger(MyDomainObject.class);

    ....
}

As far as logging "architecture" goes, let it follow your application architecture. If you have good separation of concerns in your application architecture, and have properly layered everything, and have chosen good names for your classes and interfaces, your logging structure should follow along.

Upvotes: 1

Related Questions