I have been using the following link: https://www.embedded.com/design/programming-languages-and-tools/4215552/Seventeen-steps-to-safer-C-code to enhance the current error logging of a project I am working on.
My end goal is to generate an enum "error type". I would map these error types to a lookup table of char*'s which I could use to log a more detailed explanation of what the error is.
This way, I have all my error codes and corresponding error strings in a central location and can easily modify/lookup a message and errorcode without having to dig through the code.
As a PoC, my header file contains the following:
typedef enum {
ECODE_OK = 0, // OK
ECODE_SAMPLE_ERR = 1,
ECODE_LAST
} myEcodes;
char * ecodeMap[ECODE_LAST+1];
char * ecodeName(myEcodes err);
My implementation in C of the header is included below:
char * ecodeMap[ECODE_LAST+1] =
{
"No error to report",
"Example Error Code - Invalid Value",
"Last ecode place holder"
};
char * ecodeName(myEcodes err)
{
return (char *) eyescanEcodeMap[err];
}
My question is, say I have the following code snippet to log an error I encountered:
fprintf(fp, "%s", ecodeName(ECODE_SAMPLE_ERR));
What if I want ECODE_SAMPLE_ERR to actually contain a formatted string like
"Example Error Code - Invalid Values: %d %d", myVarInt1, myVarInt2
instead of just
"Example Error Code - Invalid Value"
What would be the best way to be able to format individual strings in my array of char* such that I can include the value of variables in particular entries?
"You have lost connection to the device". Others may have several variables, i.e."The current laser settings for DAC %d, pulsewidth %d, and period %d resulted in an invalid laser power %f", var1, var2, var3, var4. I would say most won't need errors and only a very small number would ever need more than 5 variables inserted into the stringfprintf(fp, "%s", get_error_string(error_code));. Forgive me for changing the names, I tried to type it like you did but I couldn't.strerror( error );will return a suitable string for most error conditions. However, for errors specific to the application, something like this: In the code:CommonWriteCdsLog( eLL_Critical, get_pFormatString( eFormat_CFFL_string ), __FILE__, __LINE__, "LibFunc:popen() failed for 'bin/date'");worked very well for me. were ` get_pFormatString()` selected from a table of format strings andeLL_Criticalwas from aenumof values to determine if the message was to be logged. and the (cont)