Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

java - How to turn off logging for one URL log4j

I have project on old version of dropwizrd (0.9.3 where is no any log filter(https://www.dropwizard.io/en/release-0.9.x/manual/core.html#logging)) and I want to disable log for one url.

I try to use it:

package com.pack.service.services;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;


public class LogFilter extends Filter<ILoggingEvent> {

  final static String SPAM_URL = "spam";

  @Override
  public FilterReply decide(ILoggingEvent event) {
    if (!event.getMessage().contains(SPAM_URL)) {
      return FilterReply.ACCEPT;
    } else {
      return FilterReply.NEUTRAL;
    }
  }
}

And in folder resources in log4j2.xml file I added it:

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

        <Filter class="com.pack.service.services.LogFilter"/>

        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Root level="error" additivity="false">
            <AppenderRef ref="console" />
        </Root>
    </Loggers>
</Configuration>

But I got the error:

2021-04-01 16:26:33,473 main ERROR Appenders contains an invalid element or attribute "filter"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You created a Filter for Logback and tried to use it in Log4j 2. They are completely different frameworks. You can look at the MarkerFilter as an example of how to create a Filter for Log4j 2.

I should also point out that your configuration of the filter would be wrong. Log4j uses a Plugin system so you never specify class names in the configuration.

Having said that, you don't need to create your own filter. Just use Log4j's RegexFilter. Or if you want to duplicate your code you could use the ScriptFilter and write the equivalent code in any Scripting language that supports JSR 223 such as Groovy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...