例如:
int
mig_log(fmt,va_alist)
char
*fmt
va_dcl
{
va_list
ap
FILE
*fp
char
log_file[81]
struct
tm
*p_tm
time_t
clock
ap=(char
*)&va_alist
time(&clock)
p_tm=localtime(&clock)
sprintf(log_file,"%s/mig_%4d%.2d%.2d.log",
getenv("HOME"),
p_tm->tm_year+1900,
p_tm->tm_mon+1,
p_tm->tm_mday)
fp=fopen(log_file,"at")
if(fp==(FILE
*)0)
{
fprintf(stderr,"mig_err_log():can't
open
the
file
%s
!\n",log_file)
return
}
fprintf(fp,"%.2d/%.2d/%4d
%.2d:%.2d:%.2d
",
p_tm->tm_mon+1,\
p_tm->tm_mday,\
p_tm->tm_year+1900,\
p_tm->tm_hour,\
p_tm->tm_min,\
p_tm->tm_sec)
vfprintf(fp,fmt,ap)
fclose(fp)
}
这个就是写日志的函数
你这样调用:mig_log("日志开始[%s]->[%d]\n",__FILE__,__LINE__)
mig_log("日志开始!\n")都可以的
用我写的吧 实测过了的 可以直接使用void WriteSysLog(char *str)
{
char buf[512]
long MAXLEN = 10*1024*1024//10MB
time_t timep
FILE *fp = NULL
struct tm *p
time(&timep)
p = localtime(&timep)
memset(buf,0,sizeof(buf))
sprintf(buf,"%d-%d-%d %d:%d:%d : ",(1900+p->tm_year),(1+p->tm_mon),\
p->tm_mday,p->tm_hour, p->tm_min, p->tm_sec)//星期p->tm_wday
strcat(buf,str)
strcat(buf,"\r\n")
fp = fopen("./syslog.log","r")
if(fp==NULL)
{
fp = fopen("./syslog.log","w+")
}
else
{
fseek(fp,0,2)
if(ftell(fp) >= MAXLEN)
{
fclose(fp)
fp = fopen("./syslog.log","w+")
//大于10MB则清空原日志文件
}
else
{
fclose(fp)
fp = fopen("./syslog.log","a")
}
}
fwrite(buf,1,strlen(buf),fp)
fflush(fp)
fsync(fileno(fp))
fclose(fp)
}
#include <stdlib.h>#include <string.h>
#include <stdio.h>
#include <dirent.h>
#include <time.h>
#define LOGFILE "./dir_log_0"
int g_Count
//#define MAXLEN 1024
void WriteDebugLog(char *str)
int main(int argc, char **argv)
{
char str[1024]={0}
strcpy(str,"file no find")
int i=0,j=0
for (i=0i<10i++)
{
for (j=0j<50j++)
{
WriteDebugLog(str)
}
}
return 0
}
void WriteDebugLog(char *str)
{
char buf[2048]={0}
char logFileName[50]={0}
//long MAXLEN = 50*1024*1024//50MB
int iMax = 1024//1K
time_t timep
FILE *fp = NULL
struct tm *p
time(&timep)
p = localtime(&timep)
memset(buf,0,sizeof(buf))
sprintf(buf,"[%d-%d-%d %d:%d:%d][DEBUG]",(1900+p->tm_year),(1+p->tm_mon), p->tm_mday,p->tm_hour, p->tm_min, p->tm_sec)//星期p->tm_wday
strcat(buf,str)
strcat(buf,"\r\n")
strcpy(logFileName,LOGFILE)
int len = strlen(logFileName)
logFileName[len-1] = '0'+g_Count
fp = fopen(logFileName,"r")
if(fp==NULL)
{
fp = fopen(logFileName,"w+")
}
else
{
fseek(fp,0,2)//SEEK_END值为2
if( ftell(fp) >= iMax)
{
fclose(fp)
if (g_Count >= 9)
{
logFileName[len-1] = '0'
g_Count=0
}
else
{
g_Count++
logFileName[len-1] = '0'+g_Count
// printf("\n%c",'0'+g_Count)
}
fp = fopen(logFileName,"w+")
}
else
{
fclose(fp)
fp = fopen(logFileName,"a")
}
}
fwrite(buf,1,strlen(buf),fp)
fclose(fp)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)