Skip to content

Commit bc18fc5

Browse files
committed
Add logic to skip parsing and copying of a logging message if it will not be logged anyway
1 parent 4453494 commit bc18fc5

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/ulog.c

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,17 +46,21 @@ typedef struct {
4646
ulog_level_t threshold;
4747
} subscriber_t;
4848

49+
static ulog_level_t ulog_lowest_log_level();
50+
4951
// =============================================================================
5052
// local storage
5153

5254
static subscriber_t s_subscribers[ULOG_MAX_SUBSCRIBERS];
5355
static char s_message[ULOG_MAX_MESSAGE_LENGTH];
56+
static ulog_level_t s_lowest_log_level;
5457

5558
// =============================================================================
5659
// user-visible code
5760

5861
void ulog_init() {
5962
memset(s_subscribers, 0, sizeof(s_subscribers));
63+
s_lowest_log_level = ulog_lowest_log_level();
6064
}
6165

6266
// search the s_subscribers table to install or update fn
@@ -80,6 +84,8 @@ ulog_err_t ulog_subscribe(ulog_function_t fn, ulog_level_t threshold) {
8084
}
8185
s_subscribers[available_slot].fn = fn;
8286
s_subscribers[available_slot].threshold = threshold;
87+
s_lowest_log_level = ulog_lowest_log_level(); // Update lowest log level
88+
8389
return ULOG_ERR_NONE;
8490
}
8591

@@ -89,6 +95,7 @@ ulog_err_t ulog_unsubscribe(ulog_function_t fn) {
8995
for (i=0; i<ULOG_MAX_SUBSCRIBERS; i++) {
9096
if (s_subscribers[i].fn == fn) {
9197
s_subscribers[i].fn = NULL; // mark as empty
98+
s_lowest_log_level = ulog_lowest_log_level(); // Update lowest log level
9299
return ULOG_ERR_NONE;
93100
}
94101
}
@@ -109,6 +116,11 @@ const char *ulog_level_name(ulog_level_t severity) {
109116
}
110117

111118
void ulog_message(ulog_level_t severity, const char *fmt, ...) {
119+
// Do not evaluate the log message if it will never be logged
120+
if (severity < s_lowest_log_level){
121+
return;
122+
}
123+
112124
va_list ap;
113125
int i;
114126
va_start(ap, fmt);
@@ -127,4 +139,17 @@ void ulog_message(ulog_level_t severity, const char *fmt, ...) {
127139
// =============================================================================
128140
// private code
129141

142+
static ulog_level_t ulog_lowest_log_level(){
143+
ulog_level_t lowest_log_level = ULOG_ALWAYS_LEVEL;
144+
int i;
145+
for (i=0; i<ULOG_MAX_SUBSCRIBERS; i++) {
146+
if (s_subscribers[i].fn != NULL){
147+
if (s_subscribers[i].threshold < lowest_log_level) {
148+
lowest_log_level = s_subscribers[i].threshold;
149+
}
150+
}
151+
}
152+
return lowest_log_level;
153+
}
154+
130155
#endif // #ifdef ULOG_ENABLED

0 commit comments

Comments
 (0)