I need to add logging functionality for an existing code, based on a result of an operation. I was thinking of creating a class that, when constructed, receives a condition function and a function for execution. Based on the result of the condition, the code will be executed.
Example:
class auto_logger{
public:
auto_logger(const std::function<bool()>& cond,
const std::function<void()>& func): _cond(cond), _func(func) {}
virtual ~auto_logger()
{
try {
if (_cond()) {
_func();
}
} catch (...) {
}
}
private:
std::function<bool()> _cond;
std::function<void()> _func;
};
I will use this class like this:
int existing_func()
{
int res = FAILURE;
// this is the only additional code
auto_logger logger([&](){
return res == SUCCESS;
},
[](){
print_to_log();
});
do_some_stuff_that_may_throw();
res = perform_operation();
return res;
}
I would be happy to get some comments on this code. Are there any problem I am not seeing in this solution? Are there any better solutions?
std::function
) is necessary, if you use C++11's auto and a function to create the logger. Additionally, the exception handler in the dtor might hide problems. Note boost has a library for this: Boost.ScopeExit (with C++11 support) \$\endgroup\$_
. You need to be careful not to fall into the trap of using a reserved identifier. stackoverflow.com/a/228797/14065 and it looks ugly. \$\endgroup\$