How to implement an application event logger

In my application, it is necessary to register various events occurring in the application. For example, I need to register a file download event from a server and specify the download time, server IP address and so on. Structurally, all this data extends to various classes in the application.

My solution is to create a singleton class, name it, for example, "ApplicationEvents", and handle the application events in it. For example:

void OnFileDownloaded() { ... ApplicationEvents::Instance()->FileDownloaded(fileId_); } 

But this seems like a mess in the code and is almost impossible to verify.

An alternative solution would be to create an ApplicationEvent in the main function and pass it to the class constructors as a parameter. To avoid confusion in the code, you can use a decorator or proxy template.

For example: "FileDownloader" and decoration class "LoggingFileDownloader". But the structure of the application will be more complex, many classes will simply pass a pointer to ApplicationEvents through other classes, and this will probably be redundant in my case.

Which solution would be better?

+4
source share
2 answers

I do not understand why this could not be verified. You must test your logging module separately from the application, and once it is verified, just use it. You do not need to test it with the application. In addition, he flings regular code using Singleton - this is just one call to your code. One option would be to use publication / subscription (or observer) to publish consumption events, but it would be more abstract and difficult to track fir debugging. I would consider it only for other types of scenarios, for example, for many subscribers to some events. Another, more radical approach would be to use AOP, since logging is a more common example of cross-concern, but fir C ++ only has a few experimental fir AOP libraries.

+1
source

For this problem, I created a class for logging, and I highlighted it in my main program, then I use it in my classes. Since I do not want to slow down my application with logging, the log starts in another thread under Cpp11.
But I have to improve it in order to catch the standard outputs.

If you want to look at it: https://github.com/Waxo/lightweight_logger

+1
source

All Articles