Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

duplicate lines in java applet when using log4j

Tags:

java

applet

log4j

I'm trying to use log4j in an applet, but every time I refresh the page in the browser (to restart the applet) I get duplicated lines of output in the java console. The number of times the output is duplicated increases after each refresh.

This code reproduces the effect:

public class HelloWorldApplet extends JApplet {
    static Logger logger = Logger.getLogger(HelloWorldApplet.class);
    public void init() {
        BasicConfigurator.configure();
        logger.info("Hello log4j");
        System.out.println("Hello System.out");
    }
}

And this is the output that I'm seeing:

0 [thread applet-HelloWorldApplet.class-26] INFO HelloWorldApplet  - Hello log4j
Hello System.out
<refresh>
1987 [thread applet-HelloWorldApplet.class-27] INFO HelloWorldApplet  - Hello log4j
1987 [thread applet-HelloWorldApplet.class-27] INFO HelloWorldApplet  - Hello log4j
Hello System.out
<again>
3156 [thread applet-HelloWorldApplet.class-28] INFO HelloWorldApplet  - Hello log4j
3156 [thread applet-HelloWorldApplet.class-28] INFO HelloWorldApplet  - Hello log4j
3156 [thread applet-HelloWorldApplet.class-28] INFO HelloWorldApplet  - Hello log4j
Hello System.out

Clearing the classloader cache fixes it, and I know I need to clear the classloader cache to actually reload an applet, but sometimes I just want to restart it, especially when debugging. So I would like to understand:

  1. Why is this happening?
  2. Is there a way to prevent it?

Thanks!

like image 617
Steve Blackwell Avatar asked Jun 23 '26 04:06

Steve Blackwell


1 Answers

From the javadocs for BasicConfigurator:

public static void configure()

Add a ConsoleAppender that uses PatternLayout using the PatternLayout.TTCC_CONVERSION_PATTERN and prints to System.out to the root category.

So you're adding a new appender each time the applet is initialized. Try calling resetConfiguration() first.

like image 109
Mike Baranczak Avatar answered Jun 28 '26 18:06

Mike Baranczak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!