How to clear a log file programatically?

I have two log files setup in a logback file.

<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
              <fileNamePattern>/opt/loghome/${instance}/recon.%d{MM-dd-yyyy}.log.zip
              </fileNamePattern>
              <maxHistory>30</maxHistory>
        </rollingPolicy>
        <append>false</append>
        <encoder>
              <pattern>%d{MM/dd/yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%X{User} %msg%n</pattern>
        </encoder>
  </appender>

  <appender name="datafile1" class="ch.qos.logback.core.FileAppender">
        <file>/opt/loghome/datafiles/file1.log</file>
        <append>false</append>
        <encoder>
              <pattern>%msg%n</pattern>
        </encoder>
  </appender>

In java these are set up like so:

private static final Logger logger = LoggerFactory
              .getLogger(Main.class);

and

private static final Logger logger = LoggerFactory
              .getLogger("datafile1");

The first is the standard application log file. The second stores data which the program retreives from a db.

The program then compares data within the logfile and sends out some results. After this is completed, I would like to clear this log(datafile1) so it is empty and ready for the next run. How can I do this?

N.b the program is a 24hour process that uses a scheduler to run this job. It does not restart each time the job is run.

Answers


Seems that you're using the log file as a data store? Log files aren't designed for this, so there isn't actually a way to clear them. If you want to store data in a temporary location, open a file for writing, don't log it.


Ended up using this:

    public void resetLogs() {

    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); 
    ContextInitializer ci = new ContextInitializer(lc); 
    lc.reset();
    try {   
        ci.autoConfig();  
    } catch (JoranException e) {  
        e.printStackTrace(); 
    }
}

To refresh the LoggerContext context


You can try to close appender and add another appender to your Logger. Here an example:

Logger logger = Logger.getLogger("datafile1");
logger.setLevel(Level.ALL);

FileAppender appender = new FileAppender(new PatternLayout("%msg%n"), "/logs/datafile", false);
Logger.getRootLogger().addAppender(appender);

// log data
logger.info("info1");

// here you remove and close the old appender
Logger.getRootLogger().removeAppender(appender);
appender.close();

// replace with a new one appender
appender = new FileAppender(new PatternLayout("%msg%n"), "/logs/datafile", false);
Logger.getRootLogger().addAppender(appender);

// log new data
logger.info("info2");

Need Your Help

Conver varchar value as Time in oracle

oracle select time varchar

I have numerical string in varchar column need to return those values in time format