Log to same file from multiple jvms using logback

Logback includes a feature which allows multiple jvms potentially running on different hosts to log to the same log file. This feature can be enabled by setting “prudent” property of an FileAppender to true.

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
         <!-- Support multiple-JVM writing to the same log file -->
         <prudent>true</prudent>
</appender>

Note – RollingFileAppender extends FileAppender with the capability to rollover log files.

This feature is implemented using the file locking API introduced in JDK 1.4.  The two threads that contend for the same file may be in different JVMs, or one may be a Java thread and the other some native thread in the operating system. The file locks are visible to other operating system processes because Java file locking maps directly to the native operating system locking facility.
A small code snippet from the FileAppender class implementing the prudent feature from logback looks like


public class FileAppender extends OutputStreamAppender {

@Override
protected void writeOut(E event) throws IOException {
      if (prudent) {
         safeWrite(event);
      } else {
         super.writeOut(event);
      }
}

final private void safeWrite(E event) throws IOException {
     ResilientFileOutputStream resilientFOS =
             (ResilientFileOutputStream) getOutputStream();
     FileChannel fileChannel = resilientFOS.getChannel();
     if (fileChannel == null) {
        return;
     }
     FileLock fileLock = null;
     try {
       fileLock = fileChannel.lock();
       long position = fileChannel.position();
       long size = fileChannel.size();
       if (size != position) {
         fileChannel.position(size);
       }
       super.writeOut(event);
     } finally {
       if (fileLock != null) {
         fileLock.release();
     }
}

}
Advertisement

Posted on April 4, 2011, in logback and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: