Megamozg
Megamozg

Reputation: 1063

How to implement application events logger

In my application there is a need to log various events occurring in application. For example I need to log an event of downloading file from server and specify downloading time, server IP-address and so on. Structurally all that data is spread across various classes in the application.

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

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

But this looks like a mess in a code, and nearly impossible to test.

Alternative solution would be to create ApplicationEvent in main function and pass it to classes constructors as a parameter. To avoid mess in a code, decorator or proxy pattern can be used.

For example: 'FileDownloader' and decorating class 'LoggingFileDownloader'. But the structure of application will be more complicated, many classes will just pass pointer to ApplicationEvents through to other classes, and probably it's overkill in my case.

Which solution will be best?

Upvotes: 4

Views: 237

Answers (2)

Waxo
Waxo

Reputation: 1976

For this problem i've created a class for logging, and i allocate it in my main program then i use it in my classes. Because i don't want to slow my application with logging the logger runs in another thread under Cpp11.
But i must improve it to catch standard outputs.

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

Upvotes: 1

prmottajr
prmottajr

Reputation: 1824

I don't see why this would be impossible to test. You should test your logging module apart from the application and once it has been validated just use it. You don't have to test it together with the application. Also, it seams normal code, using a Singleton is just one call on your code. One alternative would be to use a publish/subscribe (or observer) to publish an consume events but it is going to be more abstract and hard to follow fir debugging I would consider it only for other types of scenarios, like, many subscribers are interested on some events. Other, more radical approach, would be to use AOP since logging is the more common example of cross concern but fir C++ there are only a few experinental libraries fir AOP.

Upvotes: 1

Related Questions