Skip to content

fix: add missing fflush(stdout) to write log message immediately (try 2)#446

Merged
stackia merged 1 commit intostackia:mainfrom
lark:logger_fix
Apr 9, 2026
Merged

fix: add missing fflush(stdout) to write log message immediately (try 2)#446
stackia merged 1 commit intostackia:mainfrom
lark:logger_fix

Conversation

@lark
Copy link
Copy Markdown
Contributor

@lark lark commented Apr 9, 2026

Without fflush(stdout), log messages have incorrect timestamp (added by syslogd or journald), or even get printed out when exit() but not startup.

Refactor to align on format of status_shared->log_entries[n].message (newline included)

Without fflush(stdout), log messages have incorrect timestamp
(added by syslogd or journald), or even get printed out when exit()
but not startup.

Refactor to align on format of status_shared->log_entries[n].message
(newline included)
@lark
Copy link
Copy Markdown
Contributor Author

lark commented Apr 9, 2026

please review carefully as it's not easy to make it right.

@stackia
Copy link
Copy Markdown
Owner

stackia commented Apr 9, 2026

LGTM but I don't have much time recently to test against your change.

I'll just merge and will do some testing when I'm free.

@stackia stackia merged commit a631948 into stackia:main Apr 9, 2026
4 of 5 checks passed
@lark
Copy link
Copy Markdown
Contributor Author

lark commented Apr 13, 2026

truncation is not handled well on the last attempt. this patch should be solid. you can integrate it with other fixes.
the key difference is not looking at format string but result string buffer. (for too long string, '\n' at the end in the format won't be honored.)

As I mentioned, it's not easy to make it right.

diff --git a/src/utils.c b/src/utils.c
index 0dfe94a..5a793da 100644
--- a/src/utils.c
+++ b/src/utils.c
@@ -117,11 +117,10 @@ int logger(loglevel_t level, const char *format, ...) {
     if (r < 0)
       return r;

-    /* Automatically add newline if format doesn't end with one */
-    if (format && strlen(format) > 0 && format[strlen(format) - 1] != '\n') {
-      if (r > (int)sizeof(message) - prefix_len - 2)
-        r = (int)sizeof(message) - prefix_len - 2;
-
+    /* Make sure newline ended, assuming r > 0 (format shouldn't be empty string "") */
+    if (r >= (int)sizeof(message) - prefix_len - 1)
+      message[sizeof(message) - 2] = '\n';
+    else if (message[prefix_len + r - 1] != '\n' ) {
       message[prefix_len + r++] = '\n';
       message[prefix_len + r] = '\0';
     }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants