Skip to content

Commit

Permalink
Add default stderr logger for logging to nullptr.
Browse files Browse the repository at this point in the history
This is useful for debugging a function that doesn't have a logger
available. It should not be used in production code, since it outputs to
stderr.
  • Loading branch information
iphydf committed Mar 16, 2018
1 parent acb25e6 commit f9c6936
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 6 deletions.
4 changes: 2 additions & 2 deletions toxcore/ccompat.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@
#endif

#ifdef __GNUC__
#define GNU_PRINTF __attribute__((__format__(__printf__, 6, 7)))
#define GNU_PRINTF(f, a) __attribute__((__format__(__printf__, f, a)))
#else
#define GNU_PRINTF
#define GNU_PRINTF(f, a)
#endif

#endif /* CCOMPAT_H */
46 changes: 43 additions & 3 deletions toxcore/logger.c
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,42 @@ struct Logger {
};


static const char *logger_level_name(LOGGER_LEVEL level)
{
switch (level) {
case LOG_TRACE:
return "TRACE";

case LOG_DEBUG:
return "DEBUG";

case LOG_INFO:
return "INFO";

case LOG_WARNING:
return "WARNING";

case LOG_ERROR:
return "ERROR";
}

return "<unknown>";
}

static void logger_stderr_handler(void *context, LOGGER_LEVEL level, const char *file, int line, const char *func,
const char *message, void *userdata)
{
// GL stands for "global logger".
fprintf(stderr, "[GL] %s %s:%d(%s): %s\n", logger_level_name(level), file, line, func, message);
}

static const Logger logger_stderr = {
logger_stderr_handler,
nullptr,
nullptr,
};


/**
* Public Functions
*/
Expand All @@ -59,10 +95,14 @@ void logger_callback_log(Logger *log, logger_cb *function, void *context, void *
log->userdata = userdata;
}

void logger_write(Logger *log, LOGGER_LEVEL level, const char *file, int line, const char *func, const char *format,
...)
void logger_write(const Logger *log, LOGGER_LEVEL level, const char *file, int line, const char *func,
const char *format, ...)
{
if (!log || !log->callback) {
if (!log) {
log = &logger_stderr;
}

if (!log->callback) {
return;
}

Expand Down
3 changes: 2 additions & 1 deletion toxcore/logger.h
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ void logger_callback_log(Logger *log, logger_cb *function, void *context, void *
* Main write function. If logging disabled does nothing.
*/
void logger_write(
Logger *log, LOGGER_LEVEL level, const char *file, int line, const char *func, const char *format, ...) GNU_PRINTF;
const Logger *log, LOGGER_LEVEL level, const char *file, int line, const char *func,
const char *format, ...) GNU_PRINTF(6, 7);


#define LOGGER_WRITE(log, level, ...) \
Expand Down

0 comments on commit f9c6936

Please sign in to comment.