feature: support outputting stderr and file logs at the same time

This commit is contained in:
luwenpeng
2024-08-21 14:55:43 +08:00
parent 415c21440f
commit aed2daa1a4
9 changed files with 47 additions and 60 deletions

View File

@@ -15,6 +15,7 @@ enum log_output
{
LOG_OUTPUT_STDERR,
LOG_OUTPUT_FILE,
LOG_OUTPUT_BOTH,
};
struct log_config
@@ -82,10 +83,6 @@ static inline enum log_level check_level(const char *level)
{
return LOG_FATAL;
}
else if (strcasecmp(level, "STATE") == 0)
{
return LOG_STATE;
}
else
{
return LOG_NONE;
@@ -141,14 +138,17 @@ static int parse_config(struct log_config *config, const char *cfg_file)
{
config->output = LOG_OUTPUT_FILE;
}
else if (strcasecmp(temp, "both") == 0)
{
config->output = LOG_OUTPUT_BOTH;
}
else
{
fprintf(stderr, "config file %s invalid log.output\n", cfg_file);
goto error_out;
}
// file
if (config->output == LOG_OUTPUT_FILE)
if (config->output == LOG_OUTPUT_FILE || config->output == LOG_OUTPUT_BOTH)
{
ptr = toml_raw_in(log_section, "file");
temp = NULL;
@@ -244,7 +244,7 @@ int log_init(const char *config_file)
return -1;
}
if (g_log_context.config.output == LOG_OUTPUT_FILE)
if (g_log_context.config.output == LOG_OUTPUT_FILE || g_log_context.config.output == LOG_OUTPUT_BOTH)
{
if (log_reopen() != 0)
{
@@ -257,7 +257,7 @@ int log_init(const char *config_file)
void log_free()
{
if (g_log_ctx->config.output == LOG_OUTPUT_FILE)
if (g_log_ctx->config.output == LOG_OUTPUT_FILE || g_log_ctx->config.output == LOG_OUTPUT_BOTH)
{
if (g_log_ctx->log_fd > 0)
{
@@ -267,12 +267,12 @@ void log_free()
}
}
int log_level_enabled(enum log_level level)
int log_level_check(enum log_level level)
{
return level >= g_log_ctx->config.level;
}
void log_reload_level(const char *config_file)
void log_level_reload(const char *config_file)
{
struct log_config config;
if (parse_config(&config, config_file) != 0)
@@ -308,18 +308,17 @@ void log_print(enum log_level level, const char *module, const char *fmt, ...)
// add end of line
p += snprintf(p, end - p, "\n");
if (g_log_ctx->config.output == LOG_OUTPUT_STDERR)
if (g_log_ctx->config.output == LOG_OUTPUT_STDERR || g_log_ctx->config.output == LOG_OUTPUT_BOTH)
{
fprintf(stderr, "%s", buf);
return;
}
else
if (g_log_ctx->config.output == LOG_OUTPUT_FILE || g_log_ctx->config.output == LOG_OUTPUT_BOTH)
{
if (g_log_ctx->log_file_reopen_day != local.tm_mday)
{
log_reopen();
}
do
{
nwrite = write(g_log_ctx->log_fd, buf, p - buf);