我有一个程序,需要在其中设置记录器格式,但由于有多个入口点(我无法控制所有入口点),我想将 System.setProperty()
调用放置在所有入口点汇聚的类的构造函数中。
主类
public static void main(String[] args) throws Exception {
String foo = "bar";
String baz = "boo";
static final String FORMATTER_CONFIG = "%1$tb %1$td, %1$tY %1$tr %4$s: %5$s%n";
SomeClass sc = new SomeClass();
sc.method1(foo);
sc.method2(baz);
try {
SomeOtherClass soc = SomeOtherClass.newInstance();
} catch (Exception e) {;
}
// Next line will update the property of the logging formatter for this instance
System.setProperty("java.util.logging.SimpleFormatter.format", FORMATTER_CONFIG);
MyThirdClass mtc = MyThirdClass.getStaticMethod(foo, baz);
Logger logger = Logger.getLogger("myProject.main");
Handler h = new FileHandler("LogHere.txt");
h.setFormatter(new SimpleFormatter());
logger.addHandler(h);
logger.setLevel(Level.INFO);
logger.info("Info level log");
logger.fine("Fine level log");
logger.finer("Finer level log");
logger.finest("Finest level log");
}
MyThirdClass
的构造函数:
public MyThirdClass() throws SecurityException {
this.classStaticVar = EntirelyDifferentClass.getVar();
logger = Logger.getLogger(this.getClass().getName());
Handler h = null;
try {
h = new FileHandler("MTC_LogHere.txt");
} catch (IOException ex) {
logger.warning("Failed to initialize custom FileHandler for MTC_LogHere.txt");
}
h.setFormatter(new SimpleFormatter());
logger.addHandler(h);
logger.setLevel(Level.INFO);
}
我想将对 System.setProperty
的调用作为 MyThirdClass
中构造函数的第一行(在调用 EntirelyDifferentClass
之前),但是当我这样做时,日志记录未根据自定义规则进行格式化。如果我将其保留在主方法中调用 MyThirdClass
之前的位置,它就会按预期工作。请注意,我还尝试将 System.setProperty
的代码块放入 getStaticMethod()
方法中。
我知道system.properties
都是静态变量,所以我必须相信在对MyThirdClass.getStaticMethod
的方法调用期间JVM中发生的任何事情都会锁定静态属性,然后才能更改它。
- 我是否正确理解了 JVM 中发生的情况?
- 由于我不控制实际生产中的所有入口点
这个程序的版本,我也不控制编译
设置也无法发出 -Djava 行命令来设置属性
这样(我也已经验证过它会起作用)我需要能够
在
MyThirdClass
中以编程方式执行此操作。我是什么 失踪/忽视,还是我只是运气不好?
最佳答案
这个答案最初是由OP Bryan编辑到上面的问题中的。 ,我已将其发布在这里并要求他亲自这样做:
For anyone wanting to know the answer, I added a static block at the class level of
MyThirdClass
:protected static Logger logger = null; static { System.setProperty("java.util.logging.SimpleFormatter.format", FORMATTER_CONFIG); logger = Logger.getLogger("myProject.MyThirdClass"); Handler h = null; try { h = new FileHandler("LogHere.txt"); } catch (Exception ex) { System.out.println("Exception"); } h.setFormatter(new SimpleFormatter()); logger.addHandler(h); logger.setLevel(Constants.LOGGING_LEVEL); }
关于java - 在另一个类中调用静态方法后未修改记录器的 System.setProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50064131/