Best way to override java.util.logging Level class to change the level strings

拈花ヽ惹草 提交于 2019-12-11 15:14:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!