Skip to content

Commit

Permalink
Guard log_printf in LOG macros with a log level check
Browse files Browse the repository at this point in the history
So that the format arguments will only be evaluated if the log is
enabled by the log level. Allow us to add more expensive logs without
impact performance when they are not enabled.

Signed-off-by: Yuxuan Shui <[email protected]>
  • Loading branch information
yshui committed Dec 20, 2018
1 parent fc57c7b commit 185c0ce
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/log.c
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ void log_set_level(struct log *l, int level) {
l->log_level = level;
}

enum log_level log_get_level(const struct log *l) {
return l->log_level;
}

attr_printf(4, 5) void log_printf(struct log *l, int level, const char *func,
const char *fmt, ...) {
assert(level <= LOG_LEVEL_FATAL && level >= 0);
Expand Down
13 changes: 12 additions & 1 deletion src/log.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ enum log_level {
};

#define LOG(level, x, ...) \
log_printf(tls_logger, LOG_LEVEL_##level, __func__, x, ##__VA_ARGS__)
do { \
if (LOG_LEVEL_##level >= log_get_level_tls()) { \
log_printf(tls_logger, LOG_LEVEL_##level, __func__, x, \
##__VA_ARGS__); \
} \
} while (0)
#define log_trace(x, ...) LOG(TRACE, x, ##__VA_ARGS__)
#define log_debug(x, ...) LOG(DEBUG, x, ##__VA_ARGS__)
#define log_info(x, ...) LOG(INFO, x, ##__VA_ARGS__)
Expand Down Expand Up @@ -55,6 +60,7 @@ attr_printf(4, 5) void log_printf(struct log *, int level, const char *func,
attr_malloc struct log *log_new(void);
attr_nonnull_all void log_destroy(struct log *);
attr_nonnull(1) void log_set_level(struct log *l, int level);
attr_pure enum log_level log_get_level(const struct log *l);
attr_nonnull_all void log_add_target(struct log *, struct log_target *);
attr_const enum log_level string_to_log_level(const char *);

Expand All @@ -74,6 +80,11 @@ static inline attr_nonnull_all void log_add_target_tls(struct log_target *tgt) {
log_add_target(tls_logger, tgt);
}

static inline attr_pure enum log_level log_get_level_tls(void) {
assert(tls_logger);
return log_get_level(tls_logger);
}

static inline void log_deinit_tls(void) {
assert(tls_logger);
log_destroy(tls_logger);
Expand Down

0 comments on commit 185c0ce

Please sign in to comment.