Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion base/hlog.c
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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) {
Comment thread
borisbat marked this conversation as resolved.
*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) {
Expand Down
12 changes: 12 additions & 0 deletions unittest/hlog_test.c
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#include <stdio.h>
#include <string.h>

#include "hlog.h"

int main(int argc, char* argv[]) {
Expand All @@ -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;
}
Loading