Flink Log4j 2.x使用Filter过滤日志类型

Flink Log4j 2.x使用Filter过滤日志类型(区别INFO、ERROR)


日志级别:
ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF

log4j官网:

https://logging.apache.org/log4j/2.x/index.html

ThresholdFilter

在官网中,有一个Filters的组件。Filters组件允许对日志事件进行评估,以确定是否或如何发布它们。Filter将在其过滤器方法之一上被调用,并将返回一个Result,这是一个Enum,具有3个值之一- ACCEPT, DENY或NEUTRAL。

如果LogEvent中的级别与配置的级别相同或更具体,则此过滤器返回onMatch结果,否则返回onMismatch值。例如,如果ThresholdFilter配置了ERROR级别,并且LogEvent包含DEBUG级别,那么onMismatch值将被返回,因为ERROR事件比DEBUG事件更高。

ThresholdFilter过滤器的原理是,如果LogEvent的日志级别被配置的高,则会执行onMatch,否则执行onMismatch。比如如果ThresholdFilter配置了INFO级别,而LogEvent是WARN、ERROR级别,那么onMatch值将会执行。而当LogEvent是DEBUG级别时,则onMismatch值将会执行。

这里有一个Threshold的过滤器,参数包含了:

  • Level:要匹配的有效日志级别。
  • onMatch: 当过滤器匹配时要采取的操作。可以是ACCEPT, DENY或NEUTRAL。缺省值为NEUTRAL。
  • onMismatch:当过滤器不匹配时采取的操作。可以是ACCEPT, DENY或NEUTRAL。缺省值为DENY。

借助于这个Threshold过滤器,可以初步实现过滤日志的功能:

显示info 级别的日志

appender.rolling.filter.threshold.type = ThresholdFilter
appender.rolling.filter.threshold.level = ERROR
appender.rolling.filter.threshold.onMatch = DENY
appender.rolling.filter.threshold.onMismatch = ACCEPT

由于log4j.properties的rootLogger.level = INFO,因此最小的日志级别就已经是INFO了,所以上面的配置可以保证当前appender的输出日志只包含INFO信息。相当于是对ERROR及以上级别的日志执行onMatch=>DENY,而对小于ERROR级别,也就是INFO级别,执行onMismatch => ACCEPT。

或者xml的配置方式:

<RollingFile name="RollingFileInfo" fileName="${logFilePath}/${logFileName}-info.log"
                     filePattern="${logFilePath}/$${date:yyyy-MM}/${logFileName}-%d{yyyy-MM-dd}_%i.log.gz">
            <Filters>
                <!-- onMatch:Action to take when the filter matches. The default value is NEUTRAL -->
                <!-- onMismatch:    Action to take when the filter does not match. The default value is DENY -->
                <!-- 级别在 ERROR 之上的都拒绝输出 -->
                <!-- 在组合过滤器中,接受使用 NEUTRAL(中立),被第一个过滤器接受的日志信息,会继续用后面的过滤器进行过滤,只有符合所有过滤器条件的日志信息,才会被最终写入日志文件 -->
                <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL"/>
                <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <PatternLayout pattern="%d{yyyy.MM.dd HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="30MB"/>
            </Policies>
        </RollingFile>

这种方式看着总感觉有点别扭,那有没有其他的Filter组件能更好地支持呢?

LevelMatchFilter

查询资料发现,有一个LevelMatchFilter的过滤器组件,其执行原理是:

如果日志级别等于${指定的日志级别},则onMatch,否则onMismatch

刚好符合我们的需求,于是此时,log4j.properties的配置文件就可以变成:

################################################################################
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance
#  with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
# limitations under the License.
################################################################################

# Allows this configuration to be modified at runtime. The file will be checked every 30 seconds.
monitorInterval=30

# This affects logging for both user code and Flink

# This affects logging for both user code and Flink
rootLogger.level = INFO
rootLogger.appenderRef.rolling.ref = RollingFileAppender
rootLogger.appenderRef.errorLogFile.ref = errorLogFile

# Uncomment this if you want to _only_ change Flink's logging
#logger.flink.name = org.apache.flink
#logger.flink.level = INFO

# The following lines keep the log level of common libraries/connectors on
# log level INFO. The root logger does not override this. You have to manually
# change the log levels here.
logger.akka.name = akka
logger.akka.level = INFO
logger.kafka.name= org.apache.kafka
logger.kafka.level = INFO
logger.hadoop.name = org.apache.hadoop
logger.hadoop.level = INFO
logger.zookeeper.name = org.apache.zookeeper
logger.zookeeper.level = INFO

# Log all infos in the given rolling file
appender.rolling.name = RollingFileAppender
appender.rolling.type = RollingFile
appender.rolling.append = true
appender.rolling.fileName = ${sys:log.file}
appender.rolling.filePattern = ${sys:log.file}.%i
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %-60c %x - %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=100MB
appender.rolling.policies.startup.type = OnStartupTriggeringPolicy
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = ${env:MAX_LOG_FILE_NUMBER:-10}
appender.rolling.filter.threshold.type = LevelMatchFilter
appender.rolling.filter.threshold.level = INFO
appender.rolling.filter.threshold.onMatch = ACCEPT
appender.rolling.filter.threshold.onMisMatch = DENY

appender.errorFile.name = errorLogFile
appender.errorFile.type = RollingFile
appender.errorFile.append = true
appender.errorFile.fileName = ${sys:log.file}.err
appender.errorFile.filePattern = ${sys:log.file}.err.%i
appender.errorFile.layout.type = PatternLayout
appender.errorFile.layout.pattern = %d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %-60c %x - %m%n
appender.errorFile.policies.type = Policies
appender.errorFile.policies.size.type = SizeBasedTriggeringPolicy
appender.errorFile.policies.size.size = 100MB
appender.errorFile.policies.startup.type = OnStartupTriggeringPolicy
appender.errorFile.strategy.type = DefaultRolloverStrategy
appender.errorFile.strategy.max = ${env:MAX_LOG_FILE_NUMBER:-10}
appender.errorFile.filter.threshold.type = LevelMatchFilter
appender.errorFile.filter.threshold.level = ERROR
appender.errorFile.filter.threshold.onMatch = ACCEPT
appender.errorFile.filter.threshold.onMisMatch = DENY

# Suppress the irrelevant (wrong) warnings from the Netty channel handler
logger.netty.name = org.apache.flink.shaded.akka.org.jboss.netty.channel.DefaultChannelPipeline
logger.netty.level = OFF

大家如果在部署flink任务时有类似的需求,可以参考上面的配置进行修改,实际上主要添加的只有filter.threshold配置参数即可。

分享一些讲解比较好的相关文章:

log4j2使用filter过滤日志

Log4j2 将不同线程不同级别日志输出到不同的文件中

log4j2中LevelRangeFilter的注意点

Log4j2的Filters配置

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Flink 中,可以通过设置 `flink-conf.yaml` 文件来配置 Flink日志输出。在该文件中,可以设置 `flink.logging.log4j2.appender.kafka` 属性来指定使用 Kafka Appender 进行日志输出。具体的配置方式如下: 1. 在 `flink-conf.yaml` 文件中添加以下配置: ``` flink.logging.log4j2.appender.kafka.type = Kafka flink.logging.log4j2.appender.kafka.name = Kafka flink.logging.log4j2.appender.kafka.topic = log_topic flink.logging.log4j2.appender.kafka.layout.type = JsonLayout flink.logging.log4j2.appender.kafka.layout.compact = true flink.logging.log4j2.appender.kafka.property.bootstrap.servers = localhost:9092 ``` 上述配置中,`flink.logging.log4j2.appender.kafka.type` 属性指定了使用 Kafka Appender 进行日志输出,`flink.logging.log4j2.appender.kafka.name` 属性指定了 Appender 的名称,`flink.logging.log4j2.appender.kafka.topic` 属性指定了 Kafka Topic 的名称,`flink.logging.log4j2.appender.kafka.layout.type` 属性指定了日志输出的格式,这里使用了 JsonLayout,`flink.logging.log4j2.appender.kafka.property.bootstrap.servers` 属性指定了 Kafka Broker 的地址。 2. 在 Flink 代码中启动流处理任务时,可以通过 `StreamExecutionEnvironment.getConfig()` 方法获取 ExecutionConfig 对象,然后通过 `ExecutionConfig.setGlobalJobParameters()` 方法将 `flink-conf.yaml` 文件中的配置加载到 ExecutionConfig 对象中,如下所示: ``` StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); ExecutionConfig config = env.getConfig(); config.setGlobalJobParameters(ParameterTool.fromPropertiesFile("/path/to/flink-conf.yaml")); ``` 上述代码中,`ParameterTool.fromPropertiesFile()` 方法可以将 `flink-conf.yaml` 文件中的配置加载到一个 ParameterTool 对象中,然后通过 `ExecutionConfig.setGlobalJobParameters()` 方法将该对象中的配置加载到 ExecutionConfig 对象中。 这样就可以使用 Kafka Appender 进行日志输出了。需要注意的是,Kafka Appender 的具体配置方式可以根据实际需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JermeryBesian

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值