diff --git a/base/hlog.c b/base/hlog.c index 092fe6ae0..19a456005 100644 --- a/base/hlog.c +++ b/base/hlog.c @@ -107,10 +107,10 @@ static void logger_init(logger_t* logger) { logger->truncate_percent = DEFAULT_LOG_TRUNCATE_PERCENT; logger->remain_days = DEFAULT_LOG_REMAIN_DAYS; logger->enable_fsync = 1; - logger_set_file(logger, DEFAULT_LOG_FILE); logger->last_logfile_ts = 0; logger->can_write_cnt = -1; hmutex_init(&logger->mutex_); + logger_set_file(logger, DEFAULT_LOG_FILE); } logger_t* logger_create() { @@ -193,12 +193,23 @@ void logger_enable_color(logger_t* logger, int on) { } void logger_set_file(logger_t* logger, const char* filepath) { + hmutex_lock(&logger->mutex_); strncpy(logger->filepath, filepath, sizeof(logger->filepath) - 1); + logger->filepath[sizeof(logger->filepath) - 1] = '\0'; // remove suffix .log char* suffix = strrchr(logger->filepath, '.'); if (suffix && strcmp(suffix, ".log") == 0) { *suffix = '\0'; } + // close the current logfile, the next write opens the new one + if (logger->fp_) { + fclose(logger->fp_); + logger->fp_ = NULL; + } + logger->cur_logfile[0] = '\0'; + logger->last_logfile_ts = 0; + logger->can_write_cnt = -1; + hmutex_unlock(&logger->mutex_); } void logger_set_max_filesize(logger_t* logger, unsigned long long filesize) { diff --git a/unittest/hlog_test.c b/unittest/hlog_test.c index 38da63aa5..1711620bb 100644 --- a/unittest/hlog_test.c +++ b/unittest/hlog_test.c @@ -1,3 +1,6 @@ +#include +#include + #include "hlog.h" int main(int argc, char* argv[]) { @@ -18,5 +21,14 @@ int main(int argc, char* argv[]) { hloge("%s", "show error"); hlogf("%s", "show fatal"); + // test switch log file after the log file is opened + hlog_set_file("hlog_test_switch.log"); + hlogi("%s", "show info in the switched file"); + const char* curfile = hlog_get_cur_file(); + if (strstr(curfile, "hlog_test_switch") == NULL) { + fprintf(stderr, "hlog_set_file did not switch the log file: %s\n", curfile); + return 1; + } + return 0; }