问题
My aim is to use the java.util.logging Level class and change the Level strings like 'FINE' to 'VERBOSE'.
public static final Level FINE = new Level("FINE", 500);
I know we can do this by extending the Level as follows:
public class MyLogLevel extends Level {
private static final long serialVersionUID = -8176160795706313070L;
private static final Level FINE = new MyLogLevel("VERBOSE", 500);
protected MyLogLevel(String name, int level) {
super(name, level);
}
}
I would like to know, is this the good way to do it or are there any better ways to do it.
回答1:
If you are running Oracle JDK or OpenJDK you can simply override the localized names of the existing levels. You do this by creating new resource bundle (properties file or resource bundle class) under the package sun.util.logging.resources
. The bundle name must be in the form of logging_LANG_COUNTRY
.
For example, here is a test program under project called LevelTest
:
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Level;
public class NewLevels {
public static void main(String[] args) {
System.out.println(Locale.getDefault());
ResourceBundle rb = ResourceBundle.getBundle("sun.util.logging.resources.logging");
System.out.println(rb.getLocale());
System.out.println(Level.FINE.getLocalizedName());
System.out.println(Level.FINER.getLocalizedName());
System.out.println(Level.FINEST.getLocalizedName());
}
}
When I execute this test the locale printed is en_US
. Therefore my resource bundle name will be logging_en_US.properties
.
The properties resource bundle will contain the following:
FINE=VERBOSE
FINER=VERBOSE
FINEST=VERBOSE
Here is a listing of the project structure:
%USERPROFILE%\Documents\Projects\LevelTest\src\NewLevels.java
%USERPROFILE%\Documents\Projects\LevelTest\src\sun\util\logging\resources\logging_en_US.properties
When I run the program I get the following output:
en_US
en_US
VERBOSE
VERBOSE
VERBOSE
On a larger project, you might have to fight some of the class loader issues to ensure that the correct resource bundle is located.
Alternatively, if you don't want to do that you can resort to creating a custom formatter.
来源:https://stackoverflow.com/questions/44827573/best-way-to-override-java-util-logging-level-class-to-change-the-level-strings