n611x007
n611x007

Reputation: 9272

Can I close and reopen log files with logback at runtime?

I'm new to logback. I quite fascinated by it but I'm not sure if it suits my use-case.

I would like to have a logger that I can stop and start. While it is stopped I would like to remove the log file from the filesystem. When logging is restarted the file should be re-created.

Is logback capable of this? While the logging is paused, should I avoid calling a Logger in my classes, or can logback handle this?

I use a slf4j.Logger currently. In the manual I saw that Appender objects implement the LifeCycle interface, which implies that they implement start(), stop() and isStarted().

I thought this means they can be stopped so I can move the file, but later on it goes:

If the appender could not be started or if it has been stopped, a warning message will be issued through logback's internal status management system. After several attempts, in order to avoid flooding the internal status system with copies of the same warning message, the doAppend() method will stop issuing these warnings.

Does it mean that I can stop it, then remove the file, then restart?

Upvotes: 2

Views: 1825

Answers (1)

Gray
Gray

Reputation: 116888

I would like to have a logger that I can stop and start. While it is stopped I would like to remove the log file from the filesystem. When logging is restarted the file should be re-created.

I'm not sure how to accomplish this programmatically but you can accomplish this via JMX if you've added jmxConfigurator to the logback.xml config file.

<configuration>
    <jmxConfigurator />
    ...

This exposes the ch.qos.logback.classic.jmx.JMXConfigurator bean which has an operation entitled reloadDefaultConfiguration. When I press that at runtime, the logfiles are reopened. See Jconsole image below. This means that a jmx client (such as the one in my SimpleJMX library for example) would be able to do that from the command line.

If you are trying to it programmatically from inside of the same application then you should be able to get ahold of the mbean and trigger the call yourself. Something like seems to work for me:

ManagementFactory.getPlatformMBeanServer().invoke(new ObjectName(
    "ch.qos.logback.classic:Name=default,Type=ch.qos.logback.classic.jmx.JMXConfigurator"),
    "reloadDefaultConfiguration", null, null);

What I would do is rename the logfile(s) to a different name(s) and then issue the reload configuration command. Then the renamed files can be archived or removed after the new files are created.

Hope this helps.

enter image description here

Upvotes: 1

Related Questions