I have a class that I need to create a csv file. So what I've done so far was that:
Created this class:
public class MyPatternLayout extends PatternLayout {
@Override
public String getFileHeader() {
return "message id, file name, start time, end time, status";
}
}
And my logback file is configured like this:
<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>
Well, what is happening to my right now is:
On my log file the header is being shown twice. Seems like it tries to create the file twice or something like that because if I use timestamp on the file's name than I have 2 files created.
If I stop the application and start it again, more 2 headers are shown on my csv file.
My log is looking like this:
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
What do I need to do to fix this issue? I want to show the header in the beginning of each file only. If I stop and start it should identify there is already a header on the file and don't add it.
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...