目录
支持的功能点
具体实现
#include
#include
#include
#include
#include
#include
#include
#include
static FILE *g_fp = NULL;
#define MAX_FILE_SZIE (30000000)
#define TIME_BUF_LEN (100)
#define LOG_BUF_LEN (2048)
typedef enum _log_level_e {
INFO = 0,
WARINIG,
ERROR,
MAX_LEVEL
} log_level_t;
typedef struct __level_str_s{
log_level_t level;
char* str;
} level_str_t;
level_str_t g_level_strs[MAX_LEVEL] = {
{INFO, "INFO"},
{WARINIG, "WARNING"},
{ERROR, "ERROR"}
};
static char* log_name = "./test.log";
static char* bak_log = "./test_bak.log";
static int g_debug = 1;
void logger_init(uint32_t ip_addr);
void logger_write(log_level_t level, char *fmt, ...);
void logger_set_debug(int debug);
void logger_uninit();
#define log_write(level, format, ...) \
logger_write(level, "[%s:%d][%s] "format, __FILE__, __LINE__, __func__, ##__VA_ARGS__) \
void logger_init(uint32_t ip_addr)
{
char log[105] = {0};
if (g_fp != NULL) {
return;
}
struct in_addr addr;
addr.s_addr = ip_addr;
snprintf(log, sizeof(log), "%s-ipc.log", inet_ntoa(addr));
g_fp = fopen(log, "wb+");
return;
}
void logger_set_debug(int debug)
{
g_debug = debug;
return;
}
static void check_file_size()
{
struct stat st;
stat(log_name, &st);
if (st.st_size < MAX_FILE_SZIE) {
return;
}
if (g_fp != NULL) {
fclose(g_fp);
g_fp = NULL;
}
if (access(bak_log, F_OK) == 0) {
remove(bak_log);
}
rename(log_name, bak_log);
g_fp = fopen(log_name, "wb");
return;
}
void logger_write(log_level_t level, char *fmt, ...)
{
if (!g_debug) {
return;
}
char out[LOG_BUF_LEN] = {0};
char date[TIME_BUF_LEN] = {0};
char logStr[1500] = {0};
va_list args;
struct tm *tp = NULL;
check_file_size();
// 转化日志数据
va_start(args, fmt);
vsprintf(logStr, fmt, args);
va_end(args);
// 获取当前日期
time_t tt;
time(&tt);
tp = localtime(&tt);
snprintf(date, sizeof(date),"%02d/%02d/%02d %02d:%02d:%02d",
tp->tm_year+1900, tp->tm_mon+1, tp->tm_mday, tp->tm_hour, tp->tm_min, tp->tm_sec);
// 生成完成日志
snprintf(out, sizeof(out),"%s [%s] %s",date, g_level_strs[level].str, logStr);
fprintf(g_fp, "%s\n", out);
fflush(g_fp);
printf("%s\n", out);
return;
}
void logger_uninit()
{
if (g_fp != NULL) {
fclose(g_fp);
}
return;
}