简体   繁体   中英

Issue in deleting a file created by rolling file using log4j2

I have configured the log4j2.xml file to delete files older than 2 minutes(for testing) to be deleted. This works fine but i am not able to delete the first file that is generated. After rollover, all files are being deleted.

I have attached an image of the project folder structure. You can see 2 logs files in the log folder. The first log file is not being deleted as the time it was created in is just around 3-4 milliseconds and also it is not being generated in the specified format.

项目文件夹结构

This is my log4j2.xml file:

    <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="trace">
    <Properties>
        <Property name="csvLog.fileName">csvLog</Property>
        <Property name="file-header">sender,flow,message</Property>
        <Property name="baseDir">logs</Property>
    </Properties>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout
                pattern="%d{yyyy-MM-dd} %-5p %c{1}:%L - %m%n" />
        </Console>
        <RollingFile name="csvFile" 
                     fileName="${baseDir}/csvLog.csv"
                     filePattern="${baseDir}/csvLog-%d{yyyy-MM-dd-HH-mm}.csv">
            <CsvParameterLayout delimiter="," header="${file-header}\n"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
             <!--   <SizeBasedTriggeringPolicy size="1 KB" /> -->
            </Policies>
            <DefaultRolloverStrategy>
               <Delete basePath="${baseDir}" maxDepth="1">
                  <IfFileName glob="csvLog*.csv" /> 
                  <IfLastModified age="2m" />
                </Delete>
            </DefaultRolloverStrategy>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Logger name="CSVLOG" level="debug" additivity="false">
            <appender-ref ref="csvFile" level="debug"/>
        </Logger>
        <Root level="debug" additivity="false">
            <AppenderRef ref="Console" level="debug"/>
        </Root>
    </Loggers>
</Configuration>

This is my trace:

    2022-03-28 23:31:17,343 main TRACE PatternProcessor.getNextTime returning 2022/03/28-23:32:00.000, nextFileTime=2022/03/28-23:31:00.000, prevFileTime=2022/03/28-23:30:00.000, current=2022/03/28-23:31:17.343, freq=EVERY_MINUTE
2022-03-28 23:31:17,345 main TRACE DefaultRolloverStrategy.purge() took 1.0 milliseconds
2022-03-28 23:31:17,345 main DEBUG RollingFileManager executing synchronous FileRenameAction[logs\csvLog-%d{yyyy-MM-dd-HH-mm}.csv to logs\csvLog-2022-03-28-23-30.csv, renameEmptyFiles=false]
2022-03-28 23:31:17,348 main TRACE Renamed file C:\Users\Pakalu\OneDrive\Desktop\CSV_Log\CSVlog\logs\csvLog-%d{yyyy-MM-dd-HH-mm}.csv to C:\Users\Pakalu\OneDrive\Desktop\CSV_Log\CSVlog\logs\csvLog-2022-03-28-23-30.csv with Files.move
2022-03-28 23:31:17,348 main DEBUG RollingFileManager executing async CompositeAction[DeleteAction[basePath=logs, options=[], maxDepth=1, conditions=[IfFileName(glob:csvLog*.csv), IfLastModified(age=PT2M)]]]
2022-03-28 23:31:17,349 Log4j2-2 DEBUG Starting DeleteAction[basePath=logs, options=[], maxDepth=1, conditions=[IfFileName(glob:csvLog*.csv), IfLastModified(age=PT2M)]]
2022-03-28 23:31:17,349 Log4j2-2 DEBUG DeleteAction complete in 7.6E-4 seconds
2022-03-28 23:31:17,350 Log4j2-2 TRACE Sorted paths:
2022-03-28 23:31:17,350 Log4j2-2 TRACE logs\csvLog-%d{yyyy-MM-dd-HH-mm}.csv (modified: 2022-03-28T18:01:17.3480474Z)
2022-03-28 23:31:17,350 Log4j2-2 TRACE logs\csvLog-2022-03-28-23-30.csv (modified: 2022-03-28T18:00:17.3403012Z)
2022-03-28 23:31:17,350 Log4j2-2 TRACE logs\csvLog-2022-03-28-23-29.csv (modified: 2022-03-28T17:59:17.3259106Z)
2022-03-28 23:31:17,350 Log4j2-2 TRACE IfFileName ACCEPTED: 'glob:csvLog*.csv' matches relative path 'csvLog-%d{yyyy-MM-dd-HH-mm}.csv'
2022-03-28 23:31:17,351 Log4j2-2 TRACE IfLastModified REJECTED: csvLog-%d{yyyy-MM-dd-HH-mm}.csv ageMillis '2' < 'PT2M'
2022-03-28 23:31:17,351 Log4j2-2 TRACE Not deleting base=logs, relative=csvLog-%d{yyyy-MM-dd-HH-mm}.csv
2022-03-28 23:31:17,351 Log4j2-2 TRACE IfFileName ACCEPTED: 'glob:csvLog*.csv' matches relative path 'csvLog-2022-03-28-23-30.csv'
2022-03-28 23:31:17,351 Log4j2-2 TRACE IfLastModified REJECTED: csvLog-2022-03-28-23-30.csv ageMillis '60011' < 'PT2M'
2022-03-28 23:31:17,351 Log4j2-2 TRACE Not deleting base=logs, relative=csvLog-2022-03-28-23-30.csv
2022-03-28 23:31:17,351 Log4j2-2 TRACE IfFileName ACCEPTED: 'glob:csvLog*.csv' matches relative path 'csvLog-2022-03-28-23-29.csv'
2022-03-28 23:31:17,351 Log4j2-2 TRACE IfLastModified ACCEPTED: csvLog-2022-03-28-23-29.csv ageMillis '120026' >= 'PT2M'
2022-03-28 23:31:17,352 Log4j2-2 TRACE Deleting logs\csvLog-2022-03-28-23-29.csv

This is my main file:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
public class App {
 private static final Logger csvlogger = LogManager.getLogger("CSVLOG");
 private static final Logger logger = LogManager.getLogger();

 public static void main(String args[]){

     SpringApplication.run(App.class);
     
     csvlogger.info("Debug Message", "Namaste", "Whats up", "hmm..ok");
     logger.info("You have made an error");
     logger.debug("Debug Message");
     
     runMe("test");
 }
 
 private static void runMe(String parameterParam){
     String parameter;
     for(int i=0; i<100; ++i) {
         parameter = parameterParam + i;
         System.out.println("log iteration: "+i);
         if (csvlogger.isDebugEnabled()) {
             csvlogger.debug(new ObjectArrayMessage("JD", "Ri", parameter));
         }

         if (csvlogger.isInfoEnabled()) {
             csvlogger.info(new ObjectArrayMessage("JD", "Ri", parameter));
         }

         csvlogger.info(new ObjectArrayMessage("JD", "Ri", parameter));
         csvlogger.info(new ObjectArrayMessage("JD", "Ri", parameter));
         csvlogger.info(new ObjectArrayMessage("JD", "Ri", parameter));
         try {
             Thread.sleep(60000);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
     }
 }
 
}

I have referred many articles on stackoverflow but not able to figure out the problem. Can anyone please help me as to how the first file is generated and how to delete it?

Any Help would be greatly appreciated. Thank you

I think this is because fileName="${baseDir}/csvLog.csv" -> is the current file for log output. It is beyong delete history. And the files filePattern="${baseDir}/csvLog-%d{yyyy-MM-dd-HH-mm}.csv - are files for rolling (renaming) - "archived log files". Each time you write info into log the csvLog.csv will be created (if not exsits). And I suppose the first step is rolling and deleting, and only then csvLog.csv will be created. See here: https://logging.apache.org/log4j/2.x/manual/appenders.html#RollingFileAppender

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM