linux C/C++ 日志打印函数

//宏定义日志文件名
#define PROCESSNAME  "log_filename"

//当日志文件大于5M时,会删除该文件,该接口使用方法 参照printf
void WriteLog(const char *fm, ...)
{
int buflen = ;
char buf[buflen];
int i = ;
memset(buf, , buflen);
va_list args;
va_start( args, fm );
vsnprintf(buf, buflen, fm,args);
va_end( args ); printf("%s\n", buf);
FILE* logfile=NULL;
char logpath[] = {};
snprintf(logpath,sizeof(logpath),"/var/log/");
if(access(logpath,)!=)
{
char cmdstr[] = {};
sprintf(cmdstr,"mkdir -p %s",logpath);
system(cmdstr);
} char fname[];
char longtime[];
time_t t;
memset(fname,,sizeof(fname));
time(&t);
struct tm local = {};
localtime_r(&t, &local);
sprintf(longtime,"%04d-%02d-%02d %02d:%02d:%02d", local.tm_year+,
local.tm_mon+, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
sprintf(fname,"%s/%s", logpath, PROCESSNAME);
for(i= ; i < ; i++)
{
logfile = fopen(fname, "ab");
if(logfile)
break;
sleep();
}
if(logfile)
{
// 判断文件大小
if (ftell(logfile) < **) // 5M
{
//日期时间
const char* pTemp = longtime;
fwrite(pTemp, , strlen(pTemp), logfile);
fwrite(" ", , , logfile);
//内容
fwrite(buf, , strlen(buf), logfile);
fwrite(" \r\n", , , logfile);
fclose(logfile);
}
else
{
fclose(logfile);
remove(fname);
}
}
}
上一篇:IOS 网络请求方式


下一篇:Java基础之扩展GUI——显示About对话框(Sketcher 2 displaying an About dialog)