Aussie AI
Error Logging
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Error Logging
Error logging is the small matter of what your code should do when it detects a problem.
This is not the question of whether to manually check for error return codes versus
a full stack of try
-catch
exception handling.
Rather, this is the question as to what either of those technically should actually do
when they get triggered.
This depends on whether your code is running on an iPhone app versus a website backend,
and includes options such as:
- Pop up a user error message on their phone.
- Pop up a GUI dialog on Windows desktop.
- Log an error message to the Apache error logs.
- Print it to stderr and hope someone's listening.
Note that there are several different types of “errors” that you need to think about:
- User input errors
- Configuration errors
- Assertion failures (internal errors)
- Self-testing failures (e.g. debug wrappers)
- External resource failures (e.g. file not found)
- Internal resource failures (e.g. memory allocation failed)
- Debug tracing messages
Some of these need to go to the user, whereas some of those you would prefer to only be seen by the software development team. On the other hand, if some of the internal errors occur, then you want a way for users to submit them to the support team, so deciding what to disclose publicly is a judgement call.
And there are also non-error messages that can often be handled by the same subsystem, such as:
- Informational messages
- Configuration reports
- Statistics tracking
- Time measurements tracking
- Supportability messages
There are a few standardized error logging classes available:
std::clog
(globaliostream
object)Boost.Log
Log4cxx
(Apache)
BYO Error Logging: It's common for professional C++ programmers to skip the standard error logging classes, and BYO. That is, Build Your Own. Typically, each project defines a simple API to log an error, and the error logging subsystem has to decide what to do.
Here's a simple version using C++ varargs preprocessor macros:
#define errprintf(fmt,...) fprintf(stderr, (fmt), __VA_ARGS__ )
This is using the special tokens “...
” in the macro parameter list and “__VA_ARGS__
” in the macro body,
which are standard C/C++ features since C99.
And since we're using this for error logging, we might sometimes want to also emit some extra context information:
#define errprintf2(fmt,...) \ fprintf(stderr, "ERROR [%s:%d:%s]: ", __FILE__, __LINE__, __func__), \ fprintf(stderr, (fmt), __VA_ARGS__ )
Note that this macro uses the comma operator between the two fprintf calls.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |