如何使用logback在我的日志文件上添加标头?

时间:2016-07-28 17:29:25

标签: csv logging logback logback-groovy

我有一个类,我需要创建一个csv文件。 所以我到目前为止所做的是:

创建此类:

public class MyPatternLayout extends PatternLayout {


    @Override
    public String getFileHeader() {
            return "message id, file name, start time, end time, status";
    }

}

我的logback文件配置如下:

    <appender name="METRICSTEST" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>metricstest.csv</file>
            <append>true</append>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>metricstest-%d{yyyy-ww}.csv.zip</fileNamePattern>
            </rollingPolicy>
            <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
                <layout class="com.mdw360.actuator.log.layout.MyPatternLayout">
                    <pattern>%msg%n</pattern>
                </layout>
            </encoder>
        </appender>
<logger name="com.mdw360.actuator.tasks.MetricsLoggingTask" level="INFO" additivity="false">
        <appender-ref ref="METRICSTEST" />
    </logger>

嗯,我现在正在发生的事情是:

  1. 在我的日志文件中,标题显示两次。似乎它试图创建文件两次或类似的东西,因为如果我在文件的名称上使用时间戳而不是我创建了2个文件。

  2. 如果我停止应用程序并再次启动它,我的csv文件会显示更多2个标题。

  3. 我的日志看起来像这样:

    message id, file name, start time, end time, status
    message id, file name, start time, end time, status
    First Line
    Second Line
    Stop Application
    message id, file name, start time, end time, status
    message id, file name, start time, end time, status
    First Line
    Second Line
    Stop Application
    

    我需要做些什么来解决这个问题?我想只在每个文件的开头显示标题。如果我停下来开始它应该确定文件上已经有标题并且不要添加它。

1 个答案:

答案 0 :(得分:0)

Well, don't know if I'm doing it the best way, but to solve this problem I made this:

@Override
    public String getFileHeader(){
        boolean constainsHeader = false;
        try {
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            String line = null;
            while ((line = br.readLine()) != null && !constainsHeader) {
                if(line.contains(header)){
                    constainsHeader = true;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        if(constainsHeader){
            return "";
        }
        return header;
    }

Basically, I open the file and go over the lines... If I find the header the I return empty...