I'm creating a simple Logging utility for an embedded C project I'm working on. This utility provides common logging capabilities (new-line append, log-levels, timestamping, etc), but we would like for each file in the project to be able to specify a "label", which should be prepended to all of that file's logs. I seem to have found a way to do this using only a header file (log.h), which simplifies the logger implementation.
In order for this to work, application files need to #define a LOG_LABEL above the #include log.h
, and log.h needs to exclude part of its body from the "wrapper #ifndef" (SRC_LOG_H_).
This is a simplified version of my log.h, for demo purposes.
// log.h
/* Application files can define LOG_LABEL above the inclusion of log.h */
#ifdef LOG_LABEL
#define _LOG_LABEL "" LOG_LABEL " : "
#else
#define _LOG_LABEL
#endif
#ifndef LOG_H_
#define LOG_H_
/* #includes ... */
/* 'private' log function. Formats logs: "[timestamp] [level] Label? : Message" */
/* ... log functions LOG_ERROR, LOG_WARN, LOG_INFO, etc ... */
#endif // LOG_H_
// main.c
#define LOG_LABEL "MAIN"
#include "log.h"
#include "other.h"
int main() {
LOG_INFO("Hello world");
goodbye();
return 0;
}
// other.c
#define LOG_LABEL "OTHER"
#include "log.h"
#include "other.h"
void goodbye(void) {
LOG_INFO("goodbye");
}
Output:
[0] [INFO ] MAIN : Hello world
[0] [INFO ] OTHER : goodbye
Can anyone point out any issues with this implementation? I'm hesitant about using it because I haven't seen this pattern used anywhere really, so I kinda suspect there are some hidden problems with it, that may only be revealed down the road. Specifically, could the fact that part of the header file is not wrapped in the "once-only" #ifndef cause any build issues? Is the pattern bad-practice for any known reason?
Thanks in advance.