Log4j2自定义过滤器 [英] Log4j2 custom filter

查看:1181
本文介绍了Log4j2自定义过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Log4J2中实现和配置自定义过滤器-基于ThresholdFilter,但打算做更多.我见过关于自定义追加程序的主题,这些主题遵循相同的插件注释语法,但没有找到有关自定义拟合程序的主题.

I'm attempting to implement and configure a custom Filter in Log4J2 - based on ThresholdFilter, but intended to do more. I've seen topics on custom appenders, which follow the same plugin annotation syntax, but haven't found a topic on custom fitlers.

MyCustomFilter.java (基于ThresholdFilter)

MyCustomFilter.java (based on ThresholdFilter)

@Plugin(name = "MyCustomFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE, printObject = true)
public class MyCustomFilter extends AbstractFilter {

    private static final long serialVersionUID = 1L;

    private final Level level;

    private MyCustomFilter(final Level level, final Result onMatch, final Result onMismatch) {
        super(onMatch, onMismatch);
        this.level = level;
    }

    @Override
    public Result filter(final Logger logger, final Level level, final Marker marker, final String msg, final Object... params) {
        return filter(level);
    }

    @Override
    public Result filter(final Logger logger, final Level level, final Marker marker, final Object msg, final Throwable t) {
        return filter(level);
    }

    @Override
    public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg, final Throwable t) {
        return filter(level);
    }

    @Override
    public Result filter(final LogEvent event) {
        return filter(event.getLevel());
    }

    private Result filter(final Level level) {
        return level.isMoreSpecificThan(this.level) ? onMatch : onMismatch;
    }

    @Override
    public String toString() {
        return level.toString();
    }

    /**
     * Create a MyCustomFilter.
     * 
     * @param level
     *            The log Level.
     * @param match
     *            The action to take on a match.
     * @param mismatch
     *            The action to take on a mismatch.
     * @return The created MyCustomFilter.
     */
    @PluginFactory
    public static MyCustomFilter createFilter(@PluginAttribute("level") final Level level, @PluginAttribute("onMatch") final Result match,
            @PluginAttribute("onMismatch") final Result mismatch) {
        final Level actualLevel = level == null ? Level.ERROR : level;
        final Result onMatch = match == null ? Result.NEUTRAL : match;
        final Result onMismatch = mismatch == null ? Result.DENY : mismatch;
        return new MyCustomFilter(actualLevel, onMatch, onMismatch);
    }

}

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>

  <MyCustomFilter level="fatal" />

  <Appenders>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%d %-5p [%c{5}.%M():%L] %m%n" />
    </Console>
  </Appenders>

  <Loggers>
    <Logger name="com.me.test.logger" level="info" additivity="false">
      <AppenderRef ref="STDOUT" />
    </Logger>

    <!-- Root Logger -->
    <Root level="warn">
      <AppenderRef ref="STDOUT" />
    </Root>
  </Loggers>

</Configuration>

LoggingRunner.java

public class LoggingRunner {

    public static void main(String[] args) {
        Logger logger = LogManager.getLogger("com.me.test.logger");

        logger.fatal("Fatal");
        logger.error("Error");
        logger.debug("Debug");
        logger.info("Info");

        System.out.println("end it");
    }

}

配置语法似乎与Apache文档中的语法相匹配,并且模仿ThresholdFilter(有效的提供的过滤器).如果我如图所示放置它,作为上下文级别的筛选器,则看不到任何错误,但是没有调用或应用该筛选器.

The configuration syntax seems to match that in the Apache documentation and mimics ThresholdFilter (a working, provided filter). If I place it as shown, as a Context level filter, I don't see any errors, but the filter isn't invoked or applied.

如果我将自定义过滤器标签移动到Appender内(这对于开箱即用的过滤器是可能的,我会得到2015-03-24 16:20:11,713 ERROR AppenderRef contains an invalid element or attribute "MyCustomFilter".

If I move my custom filter tag inside an Appender (which is possible with out-of-the-box filters, I get 2015-03-24 16:20:11,713 ERROR AppenderRef contains an invalid element or attribute "MyCustomFilter".

基于Apache Log4J2文档和示例log42j核心源代码,我认为这可以解决问题.

Based on Apache Log4J2 documentation and examples in the log42j core source, I thought this would work.

我在做什么错了?

推荐答案

可以显示配置的第一行<Configuration>元素吗?

Can you show your config's first line, the <Configuration> element?

您可以指定<Configuration status="trace">使log4j的内部日志记录出现在控制台上,这可能有助于解决问题.

You can specify <Configuration status="trace"> to make log4j's internal logging appear on the console, which may help troubleshoot the issue.

也许log4j找不到您的插件.

Perhaps log4j has trouble finding your plugin.

编译插件时,将创建序列化的插件列表文件.该文件包含您的插件的名称和二进制格式的类名.如果此文件包含在包含您的插件类的jar中,则log4j可以找到您的插件.帮助log4j查找插件的另一种方法是在配置文件中指定packages属性:

When you compile your plugin a serialized plugin listing file is created. This file contains the name of your plugin and the classname in binary format. If this file is included in the jar containing your plugin class, log4j can find your plugin. Another way to help log4j find your plugin is to specify a packages attribute your config file:

<Configuration status="trace" packages="com.me.mycustomfilterpackage"> ...

有关更多详细信息,请参见本手册页 PluginManager尝试找到插件.

For more detail, see this manual page on how the PluginManager tries to locate plugins.

这篇关于Log4j2自定义过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆