From 4c611e6767a1c664d92f387fff408f43de903cc0 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Wed, 22 Jun 2022 00:22:18 +0200 Subject: [PATCH] Cleanup log code --- src/log.c | 27 ++++++++++++++++++++++++--- src/log.h | 3 ++- src/tty.c | 19 +++++++++---------- 3 files changed, 35 insertions(+), 14 deletions(-) diff --git a/src/log.c b/src/log.c index 5366503..64a296f 100644 --- a/src/log.c +++ b/src/log.c @@ -19,9 +19,12 @@ * 02110-1301, USA. */ +#define __STDC_WANT_LIB_EXT2__ 1 // To access vasprintf + #include "config.h" #include #include +#include #include #include #include @@ -37,6 +40,7 @@ static FILE *fp; static bool log_error = false; +static char file_buffer[BUFSIZ]; static char *date_time(void) { @@ -64,14 +68,16 @@ void log_open(const char *filename) option.log_filename = automatic_filename; } + // Open log file in append write mode fp = fopen(filename, "a+"); - if (fp == NULL) { log_error = true; exit(EXIT_FAILURE); } - setvbuf(fp, NULL, _IONBF, 0); + + // Enable full buffering + setvbuf(fp, file_buffer, _IOFBF, BUFSIZ); } bool log_strip(char c) @@ -133,7 +139,21 @@ bool log_strip(char c) return strip; } -void log_write(char c) +void log_printf(const char *format, ...) +{ + char *line; + + va_list(args); + va_start(args, format); + vasprintf(&line, format, args); + va_end(args); + + fwrite(line, strlen(line), 1, fp); + + free(line); +} + +void log_putc(char c) { if (fp != NULL) { @@ -155,6 +175,7 @@ void log_close(void) { if (fp != NULL) { + fflush(fp); fclose(fp); } } diff --git a/src/log.h b/src/log.h index 0dec98b..d2a2188 100644 --- a/src/log.h +++ b/src/log.h @@ -22,6 +22,7 @@ #pragma once void log_open(const char *filename); -void log_write(char c); +void log_printf(const char *format, ...); +void log_putc(char c); void log_close(void); void log_exit(void); diff --git a/src/tty.c b/src/tty.c index bcf99b2..b0780fc 100644 --- a/src/tty.c +++ b/src/tty.c @@ -82,11 +82,15 @@ static unsigned char hex_char_index = 0; static void optional_local_echo(char c) { if (!option.local_echo) + { return; + } print(c); fflush(stdout); if (option.log) - log_write(c); + { + log_putc(c); + } } inline static bool is_valid_hex(char c) @@ -794,14 +798,7 @@ int tty_connect(void) ansi_printf_raw("[%s] ", now); if (option.log) { - log_write('['); - while (*now != '\0') - { - log_write(*now); - ++now; - } - log_write(']'); - log_write(' '); + log_printf("[%s] ", now); } next_timestamp = false; } @@ -823,7 +820,9 @@ int tty_connect(void) /* Write to log */ if (option.log) - log_write(input_char); + { + log_putc(input_char); + } socket_write(input_char);