如何根据邮件级别将邮件记录在单独的文件中

时间:2015-11-06 12:12:10

标签: java log4j

我想要做的是创建自定义日志级别(例如SentLevel,ReceivedLevel和ReadLevel)并将使用它们记录的消息存储在单独的文件中。

让我用一个例子更清楚地解释自己。每个LOC应放在单独的LOG文件中:

    logger.log(ResultadosEnviadosLevel.RESULTADOS_ENVIADOS, "sent data :)");
    logger.log(ResultadosRecibidosLevel.RESULTADOS_RECIBIDOS, "received data :-)");
    logger.log(CustomLevel.ACCION, "action!!");

今天发送的内容:         发送数据:)

今日收到的内容:         收到的数据: - )

今日行动的内容:         动作!!

我已经调查了一下,我使用的是Log4j 1.2.17。我使用DailyRollingFileAppender。问题是我记录的每条消息都存储在三个文件中。

我已通过以下方式创建了Levels:

import org.apache.log4j.Level;

public class CustomLog4jLevel extends Level {

    private static final long serialVersionUID = 6031879473353817158L;

    /**
     * Value of AccionLog4jLevel level. This value is lesser than DEBUG_INT and higher
     * than TRACE_INT}
     */
    public static final int ACCION_INT = DEBUG_INT - 10;

    /**
     * Level representing my log level
     */
    public static final Level ACCION = new CustomLog4jLevel(ACCION_INT, "ACCION", 10);

    /**
     * Constructor
     */
    protected CustomLog4jLevel(int arg0, String arg1, int arg2) {
        super(arg0, arg1, arg2);

    }

    /**
     * Checks whether logArgument is "Accion" level. If yes then returns
     * Accion}, else calls AccionLog4jLevel#toLevel(String, Level) passing
     * it Level#DEBUG as the defaultLevel.
     */
    public static Level toLevel(String logArgument) {
        if (logArgument != null && logArgument.toUpperCase().equals("ACCION")) {
            return ACCION;
        }
        return (Level) toLevel(logArgument);
    }

    /**
     * Checks whether val is AccionLog4jLevel#Accion_INT. If yes then
     * returns AccionLog4jLevel#Accion, else calls
     * AccionLog4jLevel#toLevel(int, Level) passing it Level#DEBUG as the
     * defaultLevel
     * 
     */
    public static Level toLevel(int val) {
        if (val == ACCION_INT) {
            return ACCION;
        }
        return (Level) toLevel(val, Level.DEBUG);
    }

    /**
     * Checks whether val is AccionLog4jLevel#Accion_INT. If yes
     * then returns AccionLog4jLevel#Accion, else calls Level#toLevel(int, org.apache.log4j.Level)
     * 
     */
    public static Level toLevel(int val, Level defaultLevel) {
        if (val == ACCION_INT) {
            return ACCION;
        }
        return Level.toLevel(val, defaultLevel);
    }

    /**
     * Checks whether logArgument is "Accion" level. If yes then returns
     * AccionLog4jLevel#Accion, else calls
     * Level#toLevel(java.lang.String, org.apache.log4j.Level)
     * 
     */
    public static Level toLevel(String logArgument, Level defaultLevel) {
        if (logArgument != null && logArgument.toUpperCase().equals("ACCION")) {
            return ACCION;
        }
        return Level.toLevel(logArgument, defaultLevel);
    }
}

我的log4j.xml如下:

    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" 
 "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration 
    xmlns:log4j="http://jakarta.apache.org/log4j/"
    debug="true">

    <appender name="file-daily" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="append" value="false" />
        <param name="additivity" value="false" />

        <param name="Threshold" value="ACCION"/>

        <param name="levelMin" value="ACCION" />
        <param name="levelMax" value="ACCION" />

        <!-- Colocamos los logs en la carpeta padronlogs dentro de la del Tomcat logs -->
        <param name="file" value="${catalina.home}/logs/padronLogs/hoy.log" />
        <param name="DatePattern" value=".yyyy-MM-dd" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" 
                value="%d{dd-MM-yyyy HH:mm:ss} %-5p - %m%n" />
        </layout>
    </appender>    

    <appender name="file-results-sent" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="append" value="false" />
        <param name="additivity" value="false" />

        <param name="Threshold" value="RESULTADOS_ENVIADOS"/>

        <param name="levelMin" value="RESULTADOS_ENVIADOS" />
        <param name="levelMax" value="RESULTADOS_ENVIADOS" />

        <!-- Colocamos los logs en la carpeta padronlogs dentro de la del Tomcat logs -->
        <param name="file" value="${catalina.home}/logs/padronLogs/enviados/hoy-enviados.log" />
        <param name="DatePattern" value=".yyyy-MM-dd" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" 
                value="%d{dd-MM-yyyy HH:mm:ss} %-5p - %m%n" />
        </layout>
    </appender>    

    <appender name="file-results-received" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="append" value="false" />
        <param name="additivity" value="false" />

        <param name="Threshold" value="RESULTADOS_RECIBIDOS"/>

        <param name="levelMin" value="RESULTADOS_RECIBIDOS" />
        <param name="levelMax" value="RESULTADOS_RECIBIDOS" />

        <!-- Colocamos los logs en la carpeta padronlogs dentro de la del Tomcat logs -->
        <param name="file" value="${catalina.home}/logs/padronLogs/recibidos/hoy-recibidos.log" />
        <param name="DatePattern" value=".yyyy-MM-dd" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" 
                value="%d{dd-MM-yyyy HH:mm:ss} %-5p - %m%n" />
        </layout>
    </appender>    

    <!-- Limitar la categoria y especificar la prioridad -->
    <category name="com.ingartek.accion">
        <priority value="ACCION" class="com.ingartek.log4j.CustomLog4jLevel" />
        <appender-ref ref="file-daily" />
    </category>

    <category name="com.ingartek.enviados">
        <priority value="RESULTADOS_ENVIADOS" class="com.ingartek.log4j.ResultadosEnviadosLevel" />
        <appender-ref ref="file-results-sent"/>
    </category>
    <category name="com.ingartek.recibidos">
        <priority value="RESULTADOS_RECIBIDOS" class="com.ingartek.log4j.ResultadosRecibidosLevel" />
        <appender-ref ref="file-results-received"/>
    </category>
    <root>
        <level value="info" />
<!--        Solamente mostraremos info relacionada con solicitudes y consultas -->
        <appender-ref ref="file-daily" />
        <appender-ref ref="file-results-sent" />
        <appender-ref ref="file-results-received" />
    </root>

</log4j:configuration>

任何提示?谢谢:))

**编辑:**只要目标可行,我就不会关注从Log4j 1.x迁移到2.x(事实上,我已经开始在另一个项目中使用2.x)

1 个答案:

答案 0 :(得分:1)

我通过这个小设置来解决问题:

IN JAVA档案:

1.通过定义等级;

Level TEST = Level.forName("TEST", 250);

2.创建记录器;

Logger test_logger = LogManager.getLogger();

3.调用日志方法将日志附加到文件中。

test_logger.log(TEST, "test log message");

我的log4j2.xml文件是这样的:

<Configuration status="WARN">

<CustomLevels>
    <CustomLevel name="TEST" intLevel="150" />
</CustomLevels>

<Appenders>
    <File name="TestFile" fileName="/var/tmp/logs/test.log">
        <PatternLayout pattern="%d %-7level %logger{36} - %msg%n" />
    </File>
</Appenders>

<Loggers>
    <Root level="WARN">
        <AppenderRef ref="TestFile" level="test" />
    </Root>
</Loggers>

</Configuration>

log4j2.xml文件放在src文件夹中。 还有一件事;我使用的是log4j-api-2.3.jar,log4j-core-2.3.jar

尝试使用此配置,可能对您有所帮助。 :)