Question: I have to log to separate log files depending on the service being used. So lets say I have service1 & service2 and the logs are going to service1.log & service2.log respectively.

The issue is that there is some common code being used from both the services. Now how do I make the logs such that if the common code is called by any of the service then log into that specific log file.

The way I am create the logger is

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

```

The way I am thinking to handles this is by passing a string (logger name) to the common code and creating the logger at the method level instead of class.

Example:

```
someMethodInCommonCode(String loggerName) {
  Logger logger = Logger.getLogger(loggerName);
}

```

I have read that log4j maintains a cache of loggers so create a logger in method won't be a overhead I guess.

And yes I don't like logger name being passed. So is there a way or any configuration by which I can achieve the above scenario or any other ideas.

Answer: 
You can use the *Nested/Mapped Diagnostic Context* (NDC or MDC) feature of log4j. Essentially, these are "out of band" information which are stored on a per-thread basis and automatically attached to logging events when a log operation is performed. The information in NDC can be output to the log file or used to route log messages between appenders, and that is what you exactly need. You can find more information on these [on the official wiki of log4j](http://wiki.apache.org/logging-log4j/NDCvsMDC).

You can store the service name or some other identifier into the NDC in your services, before calling the common code. Then you can configure a log4j filter to route the common log messages to the appropriate output file according to the service name found in the NDC. The common code doesn't even need to be modified.
If your services run in different threads you can check the current thread and choose the logger accordingly