Improve timestamp function

Timestamp accuracy reaches milliseconds. If log file is used, the timestamp will also be saved.
This commit is contained in:
ottochen 2020-09-04 17:54:12 +08:00
parent 39a8f63640
commit 65758f351b
3 changed files with 18 additions and 1 deletions

View file

@ -24,6 +24,7 @@
void log_open(const char *filename); void log_open(const char *filename);
void log_write(char c); void log_write(char c);
void log_write_str(const char * str);
void log_close(void); void log_close(void);
void log_exit(void); void log_exit(void);

View file

@ -49,6 +49,13 @@ void log_write(char c)
fputc(c, fp); fputc(c, fp);
} }
void log_write_str(const char * str)
{
if (fp != NULL)
fputs(str, fp);
}
void log_close(void) void log_close(void)
{ {
if (fp != NULL) if (fp != NULL)

View file

@ -35,6 +35,7 @@
#include <stdbool.h> #include <stdbool.h>
#include <errno.h> #include <errno.h>
#include <time.h> #include <time.h>
#include <sys/time.h>
#include "config.h" #include "config.h"
#include "tio/tty.h" #include "tio/tty.h"
#include "tio/print.h" #include "tio/print.h"
@ -641,8 +642,16 @@ int tty_connect(void)
/* Print timestamp on new line, if desired. */ /* Print timestamp on new line, if desired. */
if (next_timestamp && input_char != '\n' && input_char != '\r') if (next_timestamp && input_char != '\n' && input_char != '\r')
{ {
fprintf(stdout, ANSI_COLOR_GRAY "[%s] " ANSI_COLOR_RESET, current_time()); char current_str[128];
struct timeval tv;
struct tm *tm;
gettimeofday(&tv, NULL);
tm = localtime(&tv.tv_sec);
sprintf(current_str, "[%-2d:%02d:%02d.%03ld] ", tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec/1000);
fprintf(stdout, ANSI_COLOR_GRAY "%s" ANSI_COLOR_RESET, current_str);
next_timestamp = 0; next_timestamp = 0;
if (option.log && option.timestamp)
log_write_str(current_str);
} }
/* Map input character */ /* Map input character */