问题
I was wondering, if it is possible to extend the standard java logger (java.util.logging.Logger;) for another logger level.
The goal is, that there should show up "ERROR" instead of "SEVERE" in the log files.
Is that possible? Or do I have to use a different logger instead (e.g. Log4j)?
Thanks a lot!
回答1:
If you just want to print something different than the standard you could set your own formatter, see http://tutorials.jenkov.com/java-logging/formatters.html
If you want to add an additional log level you can do so by subclassing java.util.logging.Level:
public class MyErrorLevel extends java.util.logging.Level {
public MyErrorLevel() {
super("ERROR", 1000);
}
}
回答2:
Ok, Andreas Vogler's version works. Create this class:
public class MyErrorLevel extends java.util.logging.Level
{
public MyErrorLevel()
{
super("ERROR", 1000);
}
}
To use it in your running program code, you have to do it that way:
logger.log(new MyErrorLevel(),"My Error number one");
If you need more than one errorLevel you can do it that way:
public class MyErrorLevel extends Level
{
public static MyErrorLevel ERROR = new MyErrorLevel ("ERROR", 950);
public static MyErrorLevel SERIOUS_ERROR = new MyErrorLevel("SERIOUS_ERROR", 980);
//...and so on...
private MyErrorLevel(String name, int value)
{
super (name, value);
}
}
In your program code, you can use it like this:
logger.log(MyErrorLevel.ERROR, "my other error");
logger.log(MyErrorLevel.SERIOUS_ERROR, "my significant Error");
Now, if you don't want to specify your own classname (MyErrorLevel.SERIOUS_ERROR) everytime and instead you want to use 'standard-methods' (e. g. like the already existing method logger.info("my information")
) you may think about extending the logger itself with new methods. This should (as far as my understanding goes) basically work like that:
public class MyLogger extends Logger
{
public MyLogger(String name, String resourceBundleName)
{
super(name, resourceBundleName);
}
public void error(String msg)
{
super.log(MyErrorLevel.ERROR, msg);
}
public void error(String msg)
{
super.log(MyErrorLevel.SERIOUS_ERROR, msg);
}
}
Now you should be able to call these methods in your code like that:
myLogger.error("my error")
myLogger.seriousError("my serious error")
But I wasnt able to do it: I couldn't initialize my own logger with:
MyLogger myLogger = MyLogger.getLogger("MyModifiedLogger");
This doesn't compile because of type mismatch (Cannont convert from logger to MyLogger). I also tried:
MyLogger myLogger = (MyLogger)Logger.getLogger("MyModifiedLogger");
This results in an error message while running: java.util.logging.Logger cannot be cast to utility.MyLogger So somehow my extension failed. Any ideas what I am missing?
来源:https://stackoverflow.com/questions/28451374/extend-java-logging-for-another-log-level