Cleanup log code

This commit is contained in:
Martin Lund 2022-06-22 00:22:18 +02:00
parent c82b7e2ecc
commit 4c611e6767
3 changed files with 35 additions and 14 deletions

View file

@ -19,9 +19,12 @@
* 02110-1301, USA.
*/
#define __STDC_WANT_LIB_EXT2__ 1 // To access vasprintf
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <time.h>
@ -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);
}
}

View file

@ -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);

View file

@ -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);