Extend Log4J and evitate the error Repository is null
I have seen that on the web there are few guide on how to extend Log4j.
Now i show to you how to create an extension with a timer function for Log4J.
If you have extended yet a class but have error on “repository nulla” like:
NullPointerException when extending Log4j Logger class
You must to see this extension and resolve that problem. Because you must to use the LogManager istance.
import org.apache.log4j.Logger; public class LogHelper extends Logger { final int _whitespace = 20; protected Logger target; public LogHelper(Logger target) { super(target.getName()); this.target = target; } public void timer(String msg, Long timerMillisecond) { _timer(msg, timerMillisecond); } public void timer(Long timerMillisecond) { _timer("", timerMillisecond); } private void _timer(String msg, Long timerMillisecond) { StringBuilder builder = new StringBuilder(_whitespace); String strLog = ""; strLog = "TIMER: "+timerMillisecond+"ms"; builder.append(strLog); int whiteSpace = _whitespace-builder.length(); for(int i = 0; i <whiteSpace ; i++) { builder.append(' '); } strLog = builder.toString(); if(msg != null && msg != "") strLog = strLog.concat(" || "+msg); if(timerMillisecond < 2000) { target.info(strLog); } else { target.warn(strLog); } } public void error(String message){ if (target != null) target.error(message); } public void error(Object message, Throwable t) { if (target != null) target.error(message, t); } }
Refer Logger
The important was to set the refer to a Logger
public LogHelper(Logger target) { super(target.getName()); this.target = target; }
Wrap the log error to avoid the NullPointerException on Repository
public void error(String message){ if (target != null) target.error(message); } public void error(Object message, Throwable t) { if (target != null) target.error(message, t); }