Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant approach to error logging in C++11 application?

Tags:

c++

I'm working on a small C++11 application (an SDL2 game) and i'm having a hard time "porting" some of my object-oriented knowledge from PHP/Java to C++. For example, in order to create an elegant error logging approach, i would create a class with various adapters and centralize logging there. I already did that in C++, but i have no idea on how my classes should be using the Logger class.

In Java and PHP, i would use dependency injection, and put the Logger as a class member variable in them. But in C++, what's the proper way? I don't really think that going static would be nice.

like image 853
vinnylinux Avatar asked Oct 03 '13 17:10

vinnylinux


2 Answers

Oh man.

To me logging is similar to date/time handling: the basic case is trivial, but anything more than trivial is extremely complicated: no middle ground.

Let me advise you to look into a general purpose logging library such as Pantheios or Boost.Log.

The reason why I advice for this approach as opposed to making "your own effort", is that I know first hand how the "logging situation" goes:

  • you start with a simple "write to file" or "write to screen"
  • then you need to also log to another device
  • then you want to filter out severity levels
  • then you want to send your logs via pipes
  • then you want to turn off logging

And it all becomes very, very difficult, and the logging classes start polluting your code.

So, like I said: based on my limited experience, I would encourage you to look into the suggested libraries.

Good luck.

Edit: Boost.Log examples

Just for completeness of the post (refer to page for details).

Trivial case:

#include <boost/log/trivial.hpp>
int main(int, char*[]) {
    BOOST_LOG_TRIVIAL(trace) << "A trace severity message";
    BOOST_LOG_TRIVIAL(debug) << "A debug severity message";
    BOOST_LOG_TRIVIAL(info) << "An informational severity message";
    BOOST_LOG_TRIVIAL(warning) << "A warning severity message";
    BOOST_LOG_TRIVIAL(error) << "An error severity message";
    BOOST_LOG_TRIVIAL(fatal) << "A fatal severity message";

    return 0;
}
like image 106
Escualo Avatar answered Oct 10 '22 07:10

Escualo


One approach would be to pass a reference to a logger object around function calls. However, logging is a sort of an orthogonal aspect to application logic, so that explicitly passing that logger and having it as a member quickly becomes a nuisance and only adds artificial complexity.

I prefer having one global logger in the application. Modules can create its own loggers as child loggers of the main logger forming a hierarchy (I think this is similar to Python logging module) and control its output sink and verbosity independently if necessary.

like image 29
Maxim Egorushkin Avatar answered Oct 10 '22 05:10

Maxim Egorushkin