如何使用logback以csv格式编写logfile?

时间:2017-09-18 12:01:11

标签: java csv logback

我有一个要求,我需要使用logback以csv格式编写日志。我找到了一个我可以做的样本

    <appender name="csv" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>mylog.csv</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
    <!-- rollover daily -->
    <fileNamePattern>mylog-%d{yyyy-MM-dd}.%i.csv</fileNamePattern>
        <!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB -->
        <maxFileSize>100MB</maxFileSize>    
        <maxHistory>60</maxHistory>
        <totalSizeCap>20GB</totalSizeCap>
        </rollingPolicy>
       <encoder>
         <pattern>%msg%n</pattern>
        </encoder>
     </appender>

但是我还需要在每个文件中都有这样的标准标题: -

    Time,User,Param1,Param2

如何在每个滚动文件中添加标题

1 个答案:

答案 0 :(得分:3)

您可以实施自己的Layout,扩展Logback&#39; PatternLayout

public class LogFileHeaderPatternLayout extends PatternLayout {

    private String header;

    public void setHeader(String header) {
        this.header = header;
    }

    @Override
    public String getFileHeader() {
        return header;
    }
}

然后像这样引用它:

<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
    <layout class="x.y.z.LogFileHeaderPatternLayout">
        <header>a,b,c,d</header>
        <pattern>%msg%n</pattern>
    </layout>
</encoder>

如果Logback坚持要添加此标题evey时间,则会打开日志文件(即每次应用程序启动时),然后您可以像{I}那样对getFileHeader()进行条件化:

public String getFileHeader() {
    if (alreadyContainsHeader()) {
        return "";
    } else {
        return header;
    }
}

private boolean alreadyContainsHeader() {
    try(BufferedReader br = new BufferedReader(new FileReader(filePath))) {
        String line = null;
        while ((line = br.readLine()) != null) {
            if (line.contains(header)) {
                return true;
            } else {
                break;
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }
    return false;
}