【问题标题】:log4j file renaming strategylog4j 文件重命名策略
【发布时间】:2011-04-10 12:30:29
【问题描述】:

我正在使用 log4j 1.2.15,我想知道是否有人可以解决 log4j 正在使用的烦人的文件重命名策略。

我将尝试解释: 我正在使用以下 RollingFileAppender 创建 11 个日志文件,每个日志文件大小为 3KB。

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=server.log log4j.appender.logfile.MaxFileSize=3KB log4j.appender.logfile.MaxBackupIndex=10

问题在于,在创建新日志文件时,log4j 会创建 server.log.1、server.log.2 等...

我可以配置 log4j 以保留“.log”后缀,并创建例如 server.1.log

提前致谢 伙计

【问题讨论】:

    标签: java log4j


    【解决方案1】:

    我正在使用 xml 配置(可能没有)和 Apache Extras Companion™ for Apache log4j™(log4j 的额外库)来执行此操作。我不认为这没有额外的工作,但它可能。

    关键是使用FileNamePattern

    <appender name="logger" class="org.apache.log4j.rolling.RollingFileAppender">
        <rollingPolicy class="org.apache.log4j.rolling.FixedWindowRollingPolicy">
            <param name="FileNamePattern" value="/server.%i.log" />
            <param name="MaxIndex" value="10" />
        </rollingPolicy>
    
        <triggeringPolicy class="org.apache.log4j.rolling.SizeBasedTriggeringPolicy">
            <param name="MaxFileSize" value="3000" /> 
        </triggeringPolicy>
    </appender>
    

    【讨论】:

    • 感谢您的快速回复。我已经尝试过了,但它不起作用,恐怕属性文件中的 FileNamePattern 不起作用。任何人都可以批准吗?谢谢
    【解决方案2】:

    我使用从 Geoff Mottram 的Dated File Appender 派生的每小时迭代如下,您可以将其用作导出命名策略的示例;检查 FileAppender 的来源并查看 append 方法以查看它检查文件大小的位置,然后用您自己的类覆盖 FileAppender 以正确处理重命名:

    package com.fredcheese.log4j;
    
    import java.io.File;
    import java.util.Calendar;
    import java.util.Date;
    
    import org.apache.log4j.FileAppender;
    import org.apache.log4j.spi.LoggingEvent;
    
    /**
     * Based on biz.minaret.log4j.DatedFileAppender, 
     * decompiled with JAD,
     * revised to use optional hours.
     */
    public class DistinctDailyFileAppender extends FileAppender {
    
    public static final String DEFAULT_DIRECTORY = "logs";
    public static final String DEFAULT_SUFFIX = ".txt";
    public static final String DEFAULT_PREFIX = "";
    
    private String directory = DEFAULT_DIRECTORY;
    private String prefix = DEFAULT_PREFIX;
    private String suffix = DEFAULT_SUFFIX;
    private File currentPath = null;
    private Calendar currentCalendar = null;
    private long nextTime = 0l;
    private boolean hourly = false;
    
    /**
     * Constructor.
     */
    public DistinctDailyFileAppender() {}
    
    /**
     * This method is automatically called once by the system, 
     * immediately after all properties are set, prior to release.
     */
    public void activateOptions() {
    
        currentPath = new File(directory);
        if (!currentPath.isAbsolute()) {        
            errorHandler.error("Directory failure for appender [" + name + "] : " + directory);
            return;
        }
    
        currentPath.mkdirs();
    
        // We can write; initialize calendar
        if (currentPath.canWrite()) {
            currentCalendar = Calendar.getInstance();
        } else {
            errorHandler.error("Cannot write for appender [" + name + "] : " + directory);
            return;
        }       
    }
    
    /**
     * This is called, synchronized by parent.
     */
    public void append(LoggingEvent event) {
    
        if (layout == null) {
            errorHandler.error("No layout set for appender [" + name + "].");
            return;
        }
    
        if (currentCalendar == null) {
            errorHandler.error("Improper initialization for appender [" + name + "].");
            return;
        }
    
        long nowTime = System.currentTimeMillis();
        if (nowTime >= nextTime) {
            currentCalendar.setTime(new Date(nowTime));
            String timestamp = generateTimestamp(currentCalendar);
            nextCalendar(currentCalendar);
            nextTime = currentCalendar.getTime().getTime();
            File file = new File(currentPath, prefix + timestamp + suffix);
            fileName = file.getAbsolutePath();
            super.activateOptions();
        }
    
        if (super.qw == null) {
    
            errorHandler.error("No output stream or file set for the appender named [" + name + "].");
            return;
    
        } else {
    
            subAppend(event);
            return;
    
        }
    }
    
    protected String generateTimestamp(Calendar calendar) {
    
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minutes = calendar.get(Calendar.MINUTE);
        int seconds = calendar.get(Calendar.SECOND);
    
        StringBuffer buffer = new StringBuffer();
    
        if (year < 1000) {
            buffer.append('0');
            if (year < 100) {
                buffer.append('0');
                if (year < 10) {
                    buffer.append('0');
                }
            }
        }
        buffer.append(Integer.toString(year));
        buffer.append('-');
    
        if (month < 10) {
            buffer.append('0');
        }
        buffer.append(Integer.toString(month));
        buffer.append('-');
    
        if (day < 10) {
            buffer.append('0');
        }
        buffer.append(Integer.toString(day));
        buffer.append('_');
    
        if (hour < 10) {
            buffer.append('0');
        }
        buffer.append(Integer.toString(hour));
    
        if (minutes < 10) {
            buffer.append('0');
        }
        buffer.append(Integer.toString(minutes));
    
        if (seconds < 10) {
            buffer.append('0');
        }
        buffer.append(Integer.toString(seconds));
    
        return buffer.toString();
    }
    
    protected void nextCalendar(Calendar calendar) {
        int i = calendar.get(Calendar.YEAR);
        int j = calendar.get(Calendar.MONTH);
    
        if (hourly) { 
            int k = calendar.get(Calendar.DAY_OF_MONTH);
            int l = calendar.get(Calendar.HOUR_OF_DAY) + 1;
            calendar.clear();
            calendar.set(i, j, k, l, 0);
        } else {
            int k = calendar.get(Calendar.DAY_OF_MONTH) + 1;
            calendar.clear();
            calendar.set(i, j, k);
        }
    }
    
    public String getDirectory() {
        return directory;
    }
    
    public void setDirectory(String directory) {
        if (directory == null || directory.length() == 0) {
            this.directory = "."; // Set to here
        } else {
            this.directory = directory;
        }
    }
    
    public String getPrefix() {
        return prefix;
    }
    
    public void setPrefix(String prefix) {
        if (prefix == null) {
            this.prefix = DEFAULT_PREFIX; // Set to default
        } else {
            this.prefix = prefix;
        }
    }
    
    public String getSuffix() {
        return suffix;
    }
    
    public void setSuffix(String suffix) {
        if (suffix == null) {
            this.suffix = ""; // Set to empty, not default
        } else {
            this.suffix = suffix;
        }
    }
    
    public void setHourly(boolean hourly) {
        this.hourly = hourly;
    }
    
    public boolean isHourly() {
        return this.hourly;
    }
    }
    

    这是我的 tomcat 的 appender XML sn-p(不是指小时,但你可以从我的代码中弄清楚):

    <appender name="PRIMARY_APPENDER" class="com.fredcheese.log4j.DistinctDailyFileAppender">
      <param name="Threshold" value="DEBUG"/>
      <param name="Directory" value="X:\\apps\\logs\\cheese\\"/>
      <param name="Append" value="true"/>
    
      <param name="Prefix" value="appname_log."/>
      <param name="Suffix" value=".txt"/>
    
      <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{HH:mm:ss,SSS} %-5p [%.3t] %-14.14c{1} %m%n"/>
      </layout>
    </appender>
    

    【讨论】:

      猜你喜欢
      • 2021-05-05
      • 1970-01-01
      • 2010-12-31
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      相关资源
      最近更新 更多