RandomUser
RandomUser

Reputation: 4220

How to make multiple instances of Java program share the same logging FileHandler?

I have a Java program which runs as 3 separate processes on the same server. I would like all of the processes to share a single log file, is there a way to specify that in a logging.properties file? I am using java.util.logging to handle logging.

Currently, this is how I define my FileHandler in my logging.properties file:

java.util.logging.FileHandler.pattern=%h/log/logfile.log

This works fine for 1 instance of the program, however, if I attempt to start 3 separate instances of the program the result is:

logfile.log logfile.log.1 logfile.log.2

Any advice on this?

Thankyou

Upvotes: 2

Views: 3473

Answers (4)

Buhb
Buhb

Reputation: 7149

Logback is another logger, but it supports your case.

from the docs: http://logback.qos.ch/manual/appenders.html

check out prudent mode for FileAppender

Upvotes: 3

erickson
erickson

Reputation: 269667

Elaborating on Paul's answer, you can use a SocketHandler to direct the log events from all processes to a single process, which actually writes to a file.

Most log packages provide a simple implementation of this functionality. Another widely supported option is integration with the system's logging facility (Window's Event Log or syslogd).

Upvotes: 0

Paul
Paul

Reputation: 20061

I would write a 2nd Java program - a logger. Have the other processes send log messages to the logging program, which would then write to the single log file. You can communicate between the programs using sockets. Here's an example of how to do that.

Paul

Upvotes: 0

Laurent Pireyn
Laurent Pireyn

Reputation: 6875

Writing to the same file from different processes (the different JVMs) is not recommended.

The only safe way to do it is to somehow lock the file, open it, write to it and then close it. This considerably slows down each writing, which is generally deemed unacceptable for a logger. If you really want to go this way, you can always write your own handler.

Upvotes: 0

Related Questions