Vishal Sharma
Vishal Sharma

Reputation: 57

Generate Logs in a new directory daily according to each hour in log4j2?

I want to create a directory {date}.dir and inside this directory, I need logs for each hour in a new separate file as 0000.log, 0100.log ...2300.log.

I used rolling file appender, but it only work to create a single log file and compressed the last one. I'm using time-based triggering policy with interval = 1, which gives me a new file every day and compress the last day's.

<RollingFile name="eventLogger" fileName="/Log/webservices/linpub.log" filePattern="/Log/webservices/linpub-%d{MM-dd-yyyy}.log.gz">
        <PatternLayout>
                <Pattern>%d{MM/dd/yy HH:mm:ss.SSS} %-5p [%t] %c{1} %X{trioOperation} - %m %throwable %n</Pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
        </Policies>
</RollingFile>

I want to create a new file with name as linpub-{date}.dir and inside the file, there should be a log file for each hour.

I'm using log4j2 2.3 version.

Upvotes: 1

Views: 1758

Answers (2)

Rajashekhar Arroju
Rajashekhar Arroju

Reputation: 84

Please use below configuration:

 <appender name="dailyFileAppender" 
      class="org.apache.log4j.rolling.RollingFileAppender">
      <param name="append" value="true" />
      <param name="Threshold" value="INFO" />
      <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
      <param name="FileNamePattern" value="/temp/logs/Project-Name_%d{yyyy-MM- 
      dd-HH}.log" />
      </rollingPolicy>
      <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p 
      %-10t [%-40.40c] %x - %m%n" />
      </layout>
  </appender>

Upvotes: 1

Sambit
Sambit

Reputation: 8011

In case of <TimeBasedTriggeringPolicy interval="1" modulate="true"/>, here interval="1" means 1 day not 1 hour. If you want to achieve 1 hour basis, you have to use CronTrigger base policy. Find below the code.

<CronTriggeringPolicy schedule="0 0 0/1 1/1 * ? *" evaluateOnStartup="true"/> 

Replace the following line with the above one.

<TimeBasedTriggeringPolicy interval="1" modulate="true"/>

Also change the file name patten with this yyyy-MM-dd-HH so that you will be able to know for hourly basic. Please check and test it.

Upvotes: 1

Related Questions