[英]Best way to override java.util.logging Level class to change the level strings
My aim is to use the java.util.logging Level class and change the Level strings like 'FINE' to 'VERBOSE'. 我的目标是使用java.util.logging Level类,并将Level字符串(如“ FINE”)更改为“ VERBOSE”。
public static final Level FINE = new Level("FINE", 500);
I know we can do this by extending the Level as follows: 我知道我们可以通过如下扩展Level来做到这一点:
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. 我想知道,这是执行此操作的好方法,还是有更好的执行方法?
If you are running Oracle JDK or OpenJDK you can simply override the localized names of the existing levels. 如果您正在运行Oracle JDK或OpenJDK,则可以简单地覆盖现有级别的本地化名称。 You do this by creating new resource bundle (properties file or resource bundle class) under the package
sun.util.logging.resources
. 您可以通过在包
sun.util.logging.resources
下创建新的资源束(属性文件或资源束类)来sun.util.logging.resources
。 The bundle name must be in the form of logging_LANG_COUNTRY
. 捆绑软件名称必须采用
logging_LANG_COUNTRY
的形式。
For example, here is a test program under project called LevelTest
: 例如,这是一个名为
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
. 当我执行此测试时,打印的语言环境为
en_US
。 Therefore my resource bundle name will be logging_en_US.properties
. 因此,我的资源包名称将为
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 . 另外,如果您不想这样做,则可以诉诸创建自定义格式化程序 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.