Question

I need to use logback in a client server program, for each request that comes to server, it creates a new service which will run in a separate thread. I need to log actions that happen during service excecution. But i dont want to generate separate logger object for each service thread. I know that one solution would be to set the logger object as static. So it wont be instanciated every time but is there any standard solution for this kind of problem. bellow are some code snippets from my source code:

The server class which creates a separate servcie thread for each request:

1: a logger specific for server class.

2: for each incomming request that comes to server we generate a new thread (new instance of service class),but the question is that we dont want to have a logger instances for each service instance (i guess it is a bad practice!)

and here is the service class :

enter image description here

*:logger is defined static so it wont be instanciated for each service class instance:

Was it helpful?

Solution

i know that one solution would be to set the logger object as static so it wont be instanciated every time but is there any standard solution for this kind of problem.

This is what I do in my application. It works great.

Many of my classes have this as the first line:

public class SomeClass {
    private static final Logger LOG = LoggerFactory.getLogger(SomeClass.class);

    // the rest of the class
}

Also, if you want the log messages to reflect which overall request is the one doing the logging, you should use MDC:

One of the design goals of logback is to audit and debug complex distributed applications. Most real-world distributed systems need to deal with multiple clients simultaneously. In a typical multithreaded implementation of such a system, different threads will handle different clients. A possible but slightly discouraged approach to differentiate the logging output of one client from another consists of instantiating a new and separate logger for each client. This technique promotes the proliferation of loggers and may increase their management overhead.

Read the entire link, it does a better job of explaining MDC than I ever could.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top