RollingFileAppender以编程方式设置RollingPolicy

时间:2011-05-02 22:13:07

标签: java log4j

由于我不会进入的原因,我被迫以编程方式配置log4j appender。

我想使用RollingFileAppender,因此我可以控制保留的最大文件数。

另外,我想将此appender设置为使用TimeBasedRollingPolicy,因为它会自动处理压缩滚动文件。

问题是我看不到通过代码设置此方法的方法。通常通过属性文件设置RollingFileAppender:

log4j.appender.LOGFILE.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy

必须有办法设置这个....?任何人都可以解决一些问题,挖掘javadoc和基本的eclipse - 类方法的反射并没有揭示解决方案:(

5 个答案:

答案 0 :(得分:5)

以下是我如何覆盖log4j.xml文件以将新文件名设置为名为“TheLoggerName”的记录器,其RollingFileAppender名为“TheAppenderName”。您可以将解决方案建立在此基础之上。

import org.apache.log4j.Logger;
import org.apache.log4j.rolling.RollingFileAppender;
import org.apache.log4j.rolling.TimeBasedRollingPolicy;

...

private static void afunction(String pTheNewFileName) {

Logger logger = Logger.getLogger("TheLoggerName");
RollingFileAppender rfappender = (RollingFileAppender) logger.getAppender("TheAppenderName");
TimeBasedRollingPolicy timeBasedRollingPolicy = (TimeBasedRollingPolicy) rfappender.getRollingPolicy();
timeBasedRollingPolicy.setFileNamePattern("newfilename%d{yyyy-MM}");
timeBasedRollingPolicy.activateOptions();
rfappender.activateOptions();
}

答案 1 :(得分:4)

您可能需要log4j随播广告/附加内容才能使用rolling.RollingFileAppender。

http://logging.apache.org/log4j/companions/index.html

编辑:

这是api引用,可让您设置滚动策略。

http://logging.apache.org/log4j/companions/apidocs/org/apache/log4j/rolling/RollingFileAppender.html

答案 2 :(得分:3)

这是基于cquezel的回答。更改活动文件名上的文件名以及策略文件名模式对我来说非常有用。如果不更改活动文件名,则在轮换发生之前,当前日志不可见。在这种情况下,我只是从“Launcher”更改日志文件的名称。

private static final String LOG4J_ROLLING_FILE_NAME_TOKEN = "Launcher";

/*
 * Change the name of the the log file as configured through log4j.xml
 * by replacing the placeholder file name token ("Launcher") with the
 * a new "actionName".
 */
private static void log4jConfig(String actionName) {

    org.apache.log4j.Logger rootLogger = LogManager.getRootLogger();
    RollingFileAppender fileAppender = (RollingFileAppender)rootLogger.getAppender("fileAppender");

    // <param name="FileNamePattern" value="/var/log/Launcher.log.%d{yyyy-MM-dd}.gz"/>
    String currentLogFile = fileAppender.getFile();
    String newLogPattern = currentLogFile.replace(LOG4J_ROLLING_FILE_NAME_TOKEN, actionName);
    fileAppender.setFile(newLogPattern);

    TimeBasedRollingPolicy timeBasedRollingPolicy = (TimeBasedRollingPolicy) fileAppender.getRollingPolicy();
    String fileNamePattern = timeBasedRollingPolicy.getFileNamePattern();
    String newFileNamePattern = fileNamePattern.replace(LOG4J_ROLLING_FILE_NAME_TOKEN, actionName);;
    timeBasedRollingPolicy.setFileNamePattern(newFileNamePattern);
    timeBasedRollingPolicy.activateOptions();

    fileAppender.activateOptions();

    LOG.info("  Redirected launcher log output to log pattern: " + newFileNamePattern);
}

答案 3 :(得分:1)

我最近不得不这样做。这不使用RollingFileAppender,但我认为你会明白这个想法

    public synchronized static MNLogger getLogger() {
        if (logInstance != null) return logInstance;
        Layout layout = new PatternLayout("%d{ABSOLUTE} [%t] %c{1} %m%n");
        Logger logger=Logger.getLogger(MigrationLogger.class);
        Appender a=logger.getAppender("MigrationMemory");
        if (a ==null) {

            //log4j.appender.M=org.apache.log4j.MemoryAppender
            MemoryAppender m=new MemoryAppender();
            m.setLayout(layout);
            m.setName("MigrationMemory");
            logger.addAppender(m);          
        }
        a=logger.getAppender("MigrationDisk");
        if (a ==null) {


            String tomcat=null;
            try {
                tomcat=JSPLogger.getTomcatPath();
            } catch(Exception e) {
                try {
                    tomcat=JSPLogger.getTempDir();
                } catch (IOException e1) {
                    /* swallow*/
                }
            }
            String filename=tomcat+File.separator+"logs"+File.separator+"Migration.log";

            try {

                FileAppender f =new FileAppender(layout,filename,true);
                f.setName("MigrationDisk");
                logger.addAppender(f);
            } catch (IOException e) {
                /* swallow */
            }
//          ConsoleAppender c=new ConsoleAppender(layout);
    //      logger.addAppender(c);
        }
        logger.setLevel(Level.ALL);
        logInstance=new LoggerWrap(logger);
        return logInstance;

    }

答案 4 :(得分:-2)

此示例将为每分钟创建记录器,如果您想每天更改一次,请更改datepattern值。

<appender name="ASYNC" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="File" value="./applogs/logger.log" />           
         <param name="Append" value="true" />           
        <param name="Threshold" value="debug" />          
         <appendToFile value="true" /> 
         <param name="DatePattern" value="'.'yyyy_MM_dd_HH_mm"/> 
         <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy"> 
         <param name="fileNamePattern" value="./applogs/logger_%d{ddMMMyyyy HH:mm:ss}.log"/>
         <param name="rollOver" value="TRUE"/>   
         </rollingPolicy>            
         <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ddMMMyyyy HH:mm:ss,SSS}^[%X{l4j_mdc_key}]^[%c{1}]^ %-5p %m%n" />
         </layout>
    </appender>
    <root>
        <level value="info" />
        <appender-ref ref="ASYNC" />
    </root>