BHS
BHS

Reputation: 1021

repeated logging in log 4j in java

I used log4j in a java program. I initialized it with :

BasicConfigurator.configure(); // logger configuration
try {
     logger.setLevel(Level.DEBUG);
} catch (Exception e) {
     System.out.println("Logfile not found");
}

But, during the execution of the program i get 3 log statements instead of one. For example,

3 lines 
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00

instead of one line

1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00

Are there any extra configurations to be done to log4j to avoid this?

Upvotes: 0

Views: 2553

Answers (4)

aldux
aldux

Reputation: 2804

In my case, I was adding a new appender each time I called the BasicConfigurator.configure().

I solved it reseting the configuration:

BasicConfigurator.resetConfiguration() //reset first
BasicConfigurator.configure() // then configure

I must confess that I don't clearly understand what's going on, but it surely solved my problem.

Upvotes: 0

amit
amit

Reputation: 10872

Most probably you have more than one Appenders. See the log4j manual (Section: Appenders and Layouts):

Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy.

You can try setting the additivity flag to false.

Upvotes: 4

Nils-Petter Nilsen
Nils-Petter Nilsen

Reputation: 943

I've experienced similar behavior, and it turned out that Log4J was configured more than once; using the BasicConfigurator, but also with a log4j.xml file I had forgotten about. Could it be that there's an additional Log4J configuration somewhere on the classpath?

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500055

Well, you haven't shown how your program is executing. Here's a complete program which only shows a single line:

import org.apache.log4j.*;

public class Test
{
    public static void main(String[] args)
    {
        BasicConfigurator.configure(); // logger configuration
        Logger logger = Logger.getLogger(Test.class);
        logger.setLevel(Level.DEBUG);
        logger.info("Hello");
    }
}

Is it possible that your code really is running three times?

Upvotes: 2

Related Questions