Best Creational Pattern for loggers in a multi-threaded system?
- by Dipan Mehta
This is a follow up question on my past questions :
Concurrency pattern of logger in multithreaded application
As suggested by others, I am putting this question separately.
As the learning from the last question. In a multi-threaded environment, the logger should be made thread safe and probably asynchronous (where in messages are queued while a background thread does writing releasing the requesting object thread). The logger could be signleton or it can be a per-group logger which is a generalization of the above.
Now, the question that arise is how does logger should be assigned to the object? There are two options I can think of:
1. Object requesting for the logger:
Should each of the object call some global API such as get_logger()? Such an API returns "the" singleton or the group logger. However, I feel this involves assumption about the Application environment to implement the logger -which I think is some kind of coupling. If the same object needs to be used by other application - this new application also need to implement such a method.
2. Assign logger through some known API
The other alternative approach is to create a kind of virtual class which is implemented by application based on App's own structure and assign the object sometime in the constructor.
This is more generalized method. Unfortunately, when there are so many objects - and rather a tree of objects passing on the logger objects to each level is quite messy.
My question is there a better way to do this? If you need to pick any
one of the above, which approach is would you pick and why?
Other questions remain open about how to configure them:
How do objects' names or ID are assigned so that will be used for printing on the log messages (as the module names)
How do these objects find the appropriate properties (such as log levels, and other such parameters)
In the first approach, the central API needs to deal with all this varieties.
In the second approach - there needs to be additional work.
Hence, I want to understand from the real experience of people, as to how to write logger effectively in such an environment.