10

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.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
Dan
  • 595
  • 3
  • 7
  • 12

3 Answers3

10

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 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.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • 4
    I think the problem with that method is that if you add the file/line where the log occures to your pattern ("%l" for example), you'll always get "MyLogger" and never the real source. – electrotype Jul 13 '12 at 15:42
  • 1
    Just as a reference: this solution is described at https://books.google.es/books?id=hZBimlxiyAcC&lpg=PA162&ots=QgJm9Y3WZ9&dq=log4j%20decorator&hl=es&pg=PA163#v=onepage&q=log4j%20decorator&f=false – frb Mar 17 '15 at 15:38
6

You should never create your own Logger. I have seen many bad reason to create one, but never a good one. If you want to add some contextual information in the log statements, you can use the NDC/MDC feature of Log4J.

http://wiki.apache.org/logging-log4j/NDCvsMDC

Samarth Bhargava
  • 4,196
  • 3
  • 17
  • 16
0

Don't modify the logger - a logger is a just a convenient way to send log messages to the logging framework. The processing of the messages happens in the appenders.

So you have two options:

  1. You can tell the main appender (which is attached to the root logger), to process these messages for you. Look here: LOG4J: Modify logged message using custom appender

  2. Create a new appender which delegates to an existing appender. That way, you can attach this special appender to only some loggers.

    Just implement AppenderAttachable<E> in your appender. Then you can use <appender-ref .../> in it's configuration.

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820