tags:

views:

321

answers:

2

I have a legacy PSVM application which I'd like to redirect its logging output to unique files per execution. So, if I invoke it at 10:00, then have it redirect it's output to {thread-id}-10:00.log; and another thread of execution may begin an execution at 10:01, and its output would go to {thread-id}-10:01.log. I understand that this is not elegant.

My questions are:

  • is this possible?
  • does someone have an idea of how to approach?
  • is it possible to release/destroy an appender when it's no longer needed?

Thanks!

+2  A: 

I would start with FileAppender and derive from that to create your own. Simply modify your version to get the current thread id and append a suitable thread-id/timestamp to the file prior to creation. You would maintain (say) a map of (buffered) FileWriters keyed on thread id.

Writing appenders is quite trivial - here's a Javaworld guide on how to do it.

In the above, is it at all likely that your program will start up twice in one minute ? Would you want to append a process id or similar to maintain uniqueness ?

Brian Agnew
thanks for the quick answer! it's not the case for one thread to do it more than once. But, in any case, this is just an example for discussion purposes. the name would be scoped for uniqueness.Any ideas about how to release the file writer?
eqbridges
+1 Good tutorial link
WolfmanDragon
Re. releasing. I think you should flush the writer after every log message (to ensure writing to disk), and don't worry about releasing it. Let the JVM take everything down. Unless you're writing a lot of threads and have lots of files open. Then you may just want to keep 'n' writers open at once and close some when not being logged to. That may result in some thrashing, however :-)
Brian Agnew
turns out i just remove the appender from the logger (Logger.removeAppender()) and then close it by calling Appender.close(). E-Z!
eqbridges
A: 

It is not possible, at least not easy to do in log4j. However, if you look at SiftingAppender shipping with logback (log4j's successor), it is designed to handle the creation of appenders on runtime criteria as well as their removal when no longer needed.

If you application needs to create just one log file per application launch, you could simply name your log file based on a timestamp. Shout on the logback-user mailing list if you need further assistance.

Ceki
I'm curious to get more background as to why this is not possible. It seems to be relatively straightforward. I've followed up with a posting to logback-user. I hope you can find it there and elaborate. Thanks!
eqbridges
It depends whether you wish to configure the custom appender programmatically or via a config file. There is also the question of managing log files (one per thread) in a multi-threaded application.The original question was not very specific regarding those two issues.
Ceki