different levels (including custom level) on different appenders in log4j2

房东的猫 提交于 2020-01-26 04:30:31

问题


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>


回答1:


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

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

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.

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!");
    }
}

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. 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.

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.



来源:https://stackoverflow.com/questions/50730743/different-levels-including-custom-level-on-different-appenders-in-log4j2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!