I'm currently writting a logger (e.g. using the java logger) with which I can log activities (info, errors) to a file. This (static) logger class is used by several threads and processes.
If I have just one log file then the threads get blocked, is this right? So only one thread can write to the file?
Another solution would be to have for each thread a own log file, but this would be a bit messy.
Therefore, I tought about first keeping the log in a stream (perhaps for each thread one) and only at the end of the program write everything to a file.
Is this the best way? How can I achieve this?
You can try writing everything to a file at the end of the program, but this might use a lot of memory, and also loggers usually need to be implemented so that they'll still log most/all of their data in case of a program crash or other unexpected termination.
As an alternative, you can use a concurrent queue for logged messages, e.g. a LinkedBlockingQueue or a ConcurrentLinkedQueue, where multiple threads write their messages to the queue and a single thread reads from the queue and writes the messages to a file. With a BlockingQueue
the logging thread can call take
or poll(timeout, TimeUnit)
on the queue, causing the thread to sleep until a messages becomes available; with a ConcurrentLinkedQueue
you can have the logging thread sleep for, say, ten seconds, then wake up, flush the queue to the file, and go back to sleep for another ten seconds. In either case the threads generating the logged messages won't block.