woraphol.j
woraphol.j

Reputation: 1321

How to roll a log file programmatically in Logback

According to this link: http://logback.qos.ch/manual/appenders.html (in RollingFileAppender)

It seems to me that Logback provides only a limited way of how to roll a log file. Based on time, it can roll a log file only in specific interval like once per hour, once per minute. It does not mention how to roll a log file programmatically which is what I desire. I need some way to allow users to decide when to roll a log file and the log file will be used later by the user.

I did some research using Google but found nothing. Could you please tell me how to roll a log file programmatically

Thank in advance.

Edit: At least I need some way to specify an interval like roll a log file once a ten minutes.

Upvotes: 4

Views: 1751

Answers (2)

Andreas Covidiot
Andreas Covidiot

Reputation: 4765

within (the app start of) logback.groovy one could e.g. rollover with arbitrary complex groovy code based on this idea:

appender( 'FILE', RollingFileAppender ) {
  ...
  if ( myConditionTrue )
    component.rollover()  // directly rollover on app start / logback.groovy load
}

if one would want to rollover based on some checked condition periodically one could do it based on scan(interval):

appender( ... ){
  ...
  if ( myConditionTrue )
    component.rollover()
}
scan(30)  // reparse logback.groovy every 30 s if the setup had been changed

some nice other things are mentioned here:

  • SiftingAppender/MDC usage based on discriminator:id, MDC.put('id','<some-id>'), log.info(ClassicConstants.FINALIZE_SESSION_MARKER)
  • directly calling it from within the running app ala log.getAppender('FILE').rollover()

Upvotes: 1

kan
kan

Reputation: 28961

I suggest to make your own implementation of the TriggeringPolicy. So, make your own implementation (it will check a global variable set by user) and configure the logback with your class.

Not sure about your "Edit:". Sounds like a standard TimeBasedRollingPolicy configuration.

Upvotes: 2

Related Questions