我正在尝试转换之前在log4j 1.x中使用AppenderSkeleton编写的类,现在我正在尝试将我的服务迁移到log4j 2.6。
代码:
package com.amazon.digital.music.purchasing.scheduler.test;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
/**
* A log appender which collects the log messages.
* Automatically appends itself to the root logger.
*
*/
class LogMessagesCollector extends AppenderSkeleton {
private final List<String> messages = new ArrayList<String>();
public LogMessagesCollector() {
final Logger logger = Logger.getRootLogger();
logger.addAppender(this);
}
@Override
public boolean requiresLayout() {
return false;
}
@Override
protected void append(final LoggingEvent loggingEvent) {
messages.add(loggingEvent.getMessage().toString());
}
@Override
public void close() {
final Logger logger = Logger.getRootLogger();
logger.removeAppender(this);
}
public List<String> getMessages() {
return messages;
}
我按照链接: How to Create a Custom Appender in log4j2?了解如何在log4j2中编写自定义appender,但无法编写可替换此类的类。
任何帮助都会很棒。谢谢!
答案 0 :(得分:0)
请查看log4j-core模块的单元测试中的ListAppender。它的类似之处在于它收集列表中的日志事件。它还有一些其他功能可以方便测试,但它可以成为自定义appender的一个很好的模板。
答案 1 :(得分:0)
遇到同样的问题。这是自定义解决方案的模板
log4j2.properties
name = PropertiesConfig
property.filename = logs
appenders = basic
appender.basic.type = Basic
appender.basic.name = Basic
appender.basic.layout.type= PatternLayout
appender.basic.layout.pattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
rootLogger.level = debug
rootLogger.appenderRefs = flume
rootLogger.appenderRef.flume.ref = Basic
BasicAppender.java
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.layout.PatternLayout;
import java.io.Serializable;
@Plugin(name = "Basic", category = "Core", elementType = "appender", printObject = true)
public class BasicAppender extends AbstractAppender {
private static volatile BasicAppender instance;
public BasicAppender(final String name, final Filter filter, final Layout<? extends Serializable> layout){
super(name, filter, layout);
}
@PluginFactory
public static BasicAppender createAppender(@PluginAttribute("name") String name,
@PluginElement("Layout") Layout layout,
@PluginElement("Filters") Filter filter){
if (layout == null){
layout = PatternLayout.createDefaultLayout();
}
return new BasicAppender(name, filter, layout);
}
public static BasicAppender getInstance(){
return instance;
}
@Override
public void append(final LogEvent event){
//custom actions
}
}