#define LOG_FILE "./log.txt"
#define MAX_LOG_SIZE 20971520 //20M
#define G_LOG(fmt, ...) g_mylog(__FILE__, __LINE__, __FUNCTION__, fmt, ##__VA_ARGS__) //LOG日志宏定义
//声明
gint g_mylog (const gchar* file, gint line, const gchar* function, gchar* fmt, ...);
//实现
gint g_mylog (const gchar* file, gint line, const gchar* function, gchar* fmt, ...)
{
va_list arg;
char pre[128], tmp[1024];
long clock;
struct tm *c_ptr;
FILE *fp;
struct stat statbuff;
time( &clock );
c_ptr = localtime(&clock);
sprintf(pre, "[%04d-%02d-%02d %02d:%02d:%02d][%s:%d:%s()]",
c_ptr->tm_year+1900, c_ptr->tm_mon+1, c_ptr->tm_mday,
c_ptr->tm_hour, c_ptr->tm_min, c_ptr->tm_sec, file, line , function);
va_start(arg, fmt);
vsprintf(tmp, fmt, arg);
va_end (arg);
if(!(fp = fopen(LOG_FILE, "at"))) //以追加方式打开文件,不存在则创建
return -1;
fprintf(fp, "%s %s\n", pre, tmp);
fstat(fileno(fp), &statbuff);
if (statbuff.st_size > MAX_LOG_SIZE) //如果文件超过规定大小,则保存为back文件
{
char path[1024];
fclose(fp);
sprintf(path,"cp %s %s_bak", LOG_FILE, LOG_FILE);
system(path);
sprintf(path,"rm %s", LOG_FILE);
system(path);
}
else
{
fclose(fp);
}
return 0;
}
//用法
G_LOG("test1, %d", 8899);
G_LOG("test2");