本文介绍了log4j2中不同附加程序上的不同级别(包括定制级别)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将2个类中的特殊消息记录到DB中,也想在控制台上写所有程序日志.为了实现这一点,我为JDBC附加程序定义了一个intLevel = 50的自定义级别(managerLogsLevel),但是我无法设置log4j2.xml来达到我的确切目的.这是我的xml文件:

I wanna to log special messages in 2 of my classes into DB and also wanna to write all of my program logs on console.In order to achieve this i defined a custom level(managerLogsLevel) with intLevel=50 for JDBC appender,but i couldn't set the log4j2.xml to do my exact purpose.here is my xml file:

<CustomLevels>

    <CustomLevel name="managerLogsLevel" intLevel="50" />

</CustomLevels>

<Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="%d{yyyy-MMM-dd hh:mm:ss a } %level %c - %m %n" />
    </Console>
    <JDBC name="MySQLDatabase" tableName="phonebook_finalproject.eventlog">
        <ConnectionFactory class="ir.maktabsharif.core.base.ConnectionFactory"
            method="getConnection" />
        <Column name="time" isEventTimestamp="true" />
        <Column name="name" pattern="%logger" />
        <Column name="level" pattern="%level" />
        <Column name="description" pattern="%m" />
    </JDBC>
</Appenders>

<Loggers>

    <Root level="info" additivity="false">
        <AppenderRef ref="Console" level="info" />
    </Root>

    <Logger name="org.hibernate" level="warn" />

    <Logger name="ir.maktabsharif.api" level="managerLogsLevel" >
        <AppenderRef ref="MySQLDatabase" level="managerLogsLevel" />
        <AppenderRef ref="Console" level="info" />
    </Logger>

</Loggers>

推荐答案

正如我在评论中提到的那样,我认为自定义日志级别不是您的用例的最佳解决方案:

As I mentioned in my comments, I don't think a custom log level is the best solution for your use case:

我在评论中提出了两种不同的解决方案,但我想提供更完整的答案以及一些示例.请注意,这些示例不会将消息发送到数据库,但是您可以根据需要修改附加程序.这些示例只是为了说明您可以使用的一些通用技术.

I suggested two different solutions in my comments but I want to provide a more complete answer along with some examples. Note that these examples do not send messages to a database, but you can modify the appenders as needed. These examples are just meant to provide an illustration of some general techniques you can use.

下面的第一个Java类将使用 Marker / MarkerFilter 方法:

This first java class below will use the Marker/MarkerFilter approach:

package example;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;

public class SomeClass {

    private static final Logger LOG = LogManager.getLogger();
    private static final Marker SPECIAL_MESSAGE = MarkerManager.getMarker("SPECIAL_MESSAGE");

    public static void main(String[] args){

        if(LOG.isDebugEnabled())
            LOG.debug("This is some debug!");
        LOG.info("Here's some info!");
        //To log a special kind of message use the same logger but include the marker
        LOG.info(SPECIAL_MESSAGE, "Something special goes here");
        LOG.error("Some error happened!");
    }
}

下一课(下面)将使用特殊记录器"方法:

This next class (below) will use the "special logger" approach:

package example;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class SomeClass2 {

    private static final Logger LOG = LogManager.getLogger();
    private static final Logger SPECIAL_LOG = LogManager.getLogger("SPECIAL_LOGGER");

    public static void main(String[] args){

        if(LOG.isDebugEnabled())
            LOG.debug("This is some debug!");
        LOG.info("Here's some info!");
        //To log a special kind of message use the special logger
        SPECIAL_LOG.info("Something special goes here");
        LOG.error("Some error happened!");
    }
}

这是log4j2.xml文件,其中包含两种方法的配置:

Here is the log4j2.xml file which contains configuration for both approaches:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>

        <File name="SpecialAppender" fileName="logs/special.log" immediateFlush="false"
            append="false">
            <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <MarkerFilter marker="SPECIAL_MESSAGE" onMatch="ACCEPT" onMismatch="DENY"/>
        </File>

        <File name="SpecialAppenderNoFilter" fileName="logs/specialNoFilter.log" immediateFlush="false"
            append="false">
            <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </File>
    </Appenders>

    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console" />
        </Root>

        <!-- This logger uses the MarkerFilter method -->
        <Logger name="example.SomeClass" level="debug">
            <AppenderRef ref="SpecialAppender" />
        </Logger>

        <!-- The following logger is used for the "special logger" method -->

        <Logger name="SPECIAL_LOGGER" level="info">
            <AppenderRef ref="SpecialAppenderNoFilter" />
        </Logger>
    </Loggers>
</Configuration>

这两种方法非常相似,但是有它们的区别:

These two approaches are very similar, but do have their differences:

  1. Marker 解决方案要求您创建一个 Marker 对象,而记录器解决方案则需要第二个 Logger 对象.
  2. Marker 解决方案的输出仍然为您提供一个有意义的记录器名称,而该记录器解决方案需要一个通用的记录器名称,该名称不会为您提供有关消息生成位置的任何线索.
  3. Marker 解决方案在配置文件中需要 MarkerFilter ,而logger解决方案在配置中需要专用的 Logger .
  1. The Marker solution requires you to create a Marker object whereas the logger solution requires a second Logger object.
  2. The output of the Marker solution still provides you with a meaningful logger name whereas the logger solution requires a general logger name that does not give you any clues about where the messages were generated.
  3. The Marker solution requires a MarkerFilter in the configuration file whereas the logger solution requires a dedicated Logger in the configuration.

正如我在评论中提到的,另一个考虑因素是,如果有必要,将您的日志记录策略迁移到另一个日志记录框架将是多么容易.如果要迁移到的框架不支持标记概念,则 Marker 解决方案可能会更加困难.看来 slf4j确实支持标记,因此,如果您转到具有slf4j的框架,绑定,那么标记很有可能仍然可以工作.

As I mentioned in the comments another consideration is how easy it would be to migrate your logging strategy to another logging framework if necessary. The Marker solution might be more difficult if the framework you're migrating to does not support a marker concept. It appears that slf4j does support markers so if you move to a framework that has an slf4j binding then there's a good chance the marker would still work.

这篇关于log4j2中不同附加程序上的不同级别(包括定制级别)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:39