java 如何在代码而不是配置中创建新的 log4j ConsoleAppender?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1389501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create a new log4j ConsoleAppender in code as opposed to config?
提问by Supertux
I want to programmatically create a new log4j ConsoleAppender and add it as an appender to a logger - how do I go about instantiating one properly - using the following seems to make log4j complain - what setters do I need to use to configure it properly?
我想以编程方式创建一个新的 log4j ConsoleAppender 并将其作为附加程序添加到记录器 - 我如何正确实例化一个 - 使用以下内容似乎让 log4j 抱怨 - 我需要使用哪些设置器来正确配置它?
// log4j complains of "No output stream or file set for the appender named [null]."
logger.addAppender(new ConsoleAppender());
Presumably its a case of knowing what to set on the ConsoleAppender but I can't figure it out. I assume there's some way of getting the default layout. I just want a standard ConsoleAppender that appends to SysOut. Any guidance appreciated, thanks.
大概是知道在 ConsoleAppender 上设置什么的情况,但我无法弄清楚。我假设有一些方法可以获得默认布局。我只想要一个附加到 SysOut 的标准 ConsoleAppender。任何指导表示赞赏,谢谢。
回答by mikej
You will need to set a Writeron the appender (and then also a Layoutin order to avoid the next error that you would see.) This means that you can't use an anonymous instance as you'll need to use the setters to configure the appender. e.g.
您需要Writer在 appender 上设置 a (然后还设置 aLayout以避免您会看到下一个错误。)这意味着您不能使用匿名实例,因为您需要使用 setter 来配置附加程序。例如
ConsoleAppender ca = new ConsoleAppender();
ca.setWriter(new OutputStreamWriter(System.out));
ca.setLayout(new PatternLayout("%-5p [%t]: %m%n"));
logger.addAppender(ca);
Also, you can set the name of the appender with:
此外,您可以使用以下命令设置附加程序的名称:
ca.setName("My appender");
回答by Ronald Wildenberg
This seems to be a knownissuein log4j. You should be able to fix this either by calling activateOptionson the appender before adding it to the logger or by using a parameterized constructor for ConsoleAppender.
这似乎是log4j 中的一个已知问题。您应该能够通过activateOptions在将其添加到记录器之前调用附加程序或使用参数化构造函数来解决此问题ConsoleAppender。
What version are you using? The bug seems to exist in a rather old version.
你用的是什么版本?该错误似乎存在于相当旧的版本中。

