简体   繁体   English

如何在代码中创建新的log4j ConsoleAppender而不是config?

[英]How do I create a new log4j ConsoleAppender in code as opposed to config?

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并将其作为一个appender添加到记录器 - 我如何正确实例化 - 使用以下似乎使log4j抱怨 - 我需要使用什么setter来正确配置它?

// 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. 据推测它是一个知道在ConsoleAppender上设置什么的情况,但我无法弄明白。 I assume there's some way of getting the default layout. 我假设有一些获得默认布局的方法。 I just want a standard ConsoleAppender that appends to SysOut. 我只想要一个附加到SysOut的标准ConsoleAppender。 Any guidance appreciated, thanks. 任何指导表示赞赏,谢谢。

You will need to set a Writer on the appender (and then also a Layout in 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. 你需要在appender上设置一个Writer (然后也是一个Layout ,以避免你会看到的下一个错误。)这意味着你不能使用匿名实例,因为你需要使用setter来配置appender。 eg 例如

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: 此外,您可以使用以下命令设置appender的名称:

ca.setName("My appender");

This seems to be a known issue in log4j. 这似乎是log4j中的一个已知 问题 You should be able to fix this either by calling activateOptions on the appender before adding it to the logger or by using a parameterized constructor for ConsoleAppender . 您应该能够通过在将其添加到记录器之前调用appender上的activateOptions或使用ConsoleAppender的参数化构造函数来解决此问题。

What version are you using? 你用的是什么版本? The bug seems to exist in a rather old version. 这个bug似乎存在于一个相当旧的版本中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM