Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create MyLogger?

I use log4j for logging. And I would like to modify methods: warn(..), error(..). I would like to modify message in this methods. So, is there any way, how to create my own logger?

public class MyLogger extends Logger {

protected MyLogger(String name) {
    super(name);
}

@Override
public void error(Object message) {
    message = "test - " + message;

    super.error(message);
}

}

And in class call:

private static final Logger logger = MyLogger.getLogger(TestClass.class);

logger.error("error message");

But it, do not work. Could you help me? Thanks.

like image 327
Dan Avatar asked Mar 09 '12 07:03

Dan


1 Answers

Your problem is that:

MyLogger.getLogger(TestClass.class)

is a static method which returns original Logger class. MyLogger is ignored. The easiest approach is to wrap originally returned Logger class in the spirit of decorator pattern:

public class MyLogger extends Logger {
    final Logger target;
    protected MyLogger(Logger target) {
        this.target = target;
    }

    @Override
    public void error(Object message) {
        target.error(message);
    }

    //...

}

In order to use MyLogger decorator you must wrap original logger with it:

private static final Logger logger = 
  new MyLogger(Logger.getLogger(TestClass.class));

Consider wrapping it in custom factory.

like image 92
Tomasz Nurkiewicz Avatar answered Oct 21 '22 03:10

Tomasz Nurkiewicz