首页 > 代码库 > linux C/C++ 日志打印函数

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

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


//当日志文件大于5M时,会删除该文件,该接口使用方法 参照printf
void
WriteLog(const char *fm, ...){ int buflen = 5120; char buf[buflen]; int i = 0; memset(buf, 0, 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[128] = {0}; snprintf(logpath,sizeof(logpath),"/var/log/"); if(access(logpath,0)!=0) { char cmdstr[256] = {0}; sprintf(cmdstr,"mkdir -p %s",logpath); system(cmdstr); } char fname[256]; char longtime[200]; time_t t; memset(fname,0,sizeof(fname)); time(&t); struct tm local = {0}; localtime_r(&t, &local); sprintf(longtime,"%04d-%02d-%02d %02d:%02d:%02d", local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec); sprintf(fname,"%s/%s", logpath, PROCESSNAME); for(i= 0; i < 3; i++) { logfile = fopen(fname, "ab"); if(logfile) break; sleep(1); } if(logfile) { // 判断文件大小 if (ftell(logfile) < 5*1024*1024) // 5M { //日期时间 const char* pTemp = longtime; fwrite(pTemp, 1, strlen(pTemp), logfile); fwrite(" ", 1, 1, logfile); //内容 fwrite(buf, 1, strlen(buf), logfile); fwrite(" \r\n", 1, 3, logfile); fclose(logfile); } else { fclose(logfile); remove(fname); } }}

 

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