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, and based. 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 Are there any problem I am not seeing in this solution, are? Are there any better solutions?