Add support for automatically generated log filename

Automatically generate log filename if none is provided.

The auto generated file name is on the form:
"tio_DEVICE_YYYY-MM-DDTHH:MM:SS.log"
This commit is contained in:
Martin Lund 2022-02-19 09:28:22 +01:00
parent d8a822a3fb
commit 45210bc741
3 changed files with 45 additions and 6 deletions

View file

@ -24,6 +24,9 @@
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include <libgen.h>
#include "options.h"
#include "print.h"
#include "error.h"
@ -31,8 +34,32 @@
static FILE *fp;
static bool log_error = false;
static char *date_time(void)
{
static char date_time_string[50];
struct tm *tm;
struct timeval tv;
gettimeofday(&tv, NULL);
tm = localtime(&tv.tv_sec);
strftime(date_time_string, sizeof(date_time_string), "%Y-%m-%dT%H:%M:%S", tm);
return date_time_string;
}
void log_open(const char *filename)
{
static char automatic_filename[400];
if (filename == NULL)
{
// Generate filename if none provided ("tio_DEVICE_YYYY-MM-DDTHH:MM:SS.log")
sprintf(automatic_filename, "tio_%s_%s.log", basename((char *)option.tty_device), date_time());
filename = automatic_filename;
option.log_filename = automatic_filename;
}
fp = fopen(filename, "w+");
if (fp == NULL)
@ -46,20 +73,32 @@ void log_open(const char *filename)
void log_write(char c)
{
if (fp != NULL)
{
fputc(c, fp);
}
}
void log_close(void)
{
if (fp != NULL)
{
fclose(fp);
}
}
void log_exit(void)
{
if (option.log)
{
log_close();
}
if (log_error)
{
error_printf("Could not open log file %s (%s)", option.log_filename, strerror(errno));
}
else
{
tio_printf("Saved log to file %s", option.log_filename);
}
}