实现log日志记录功能,一种宏定义形式实现,一种函数形式实现。记录于此。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdarg.h>
enum {ERROR,WARNING,INFO,DEBUG};
//宏定义形式
#define LogRecord(_error_level,_fmt,_X...) \
do { \
time_t _current_time=time(NULL); \
char _file_name[256]="\0"; \
strftime(_file_name,sizeof(_file_name),"%Y-%m-%d_log_record.log",localtime(&_current_time)); \
FILE *_fp=NULL; \
_fp=fopen(_file_name,"a+"); \
if(_fp!=NULL) \
{ \
char _time_str[32]; \
strftime(_time_str,sizeof(_time_str),"%Y-%m-%d %H:%M:%S",localtime(&_current_time)); \
if(_error_level==ERROR) \
{ \
fprintf(_fp,"[%s]-[%s]-[%s]-[%d] :> "_fmt"\n",_time_str,"ERROR",__FILE__,__LINE__,##_X); \
} \
else if(_error_level==WARNING) \
{ \
fprintf(_fp,"[%s]-[%s]-[%s]-[%d] :> "_fmt"\n",_time_str,"WARNING",__FILE__,__LINE__,##_X); \
} \
else if(_error_level==INFO) \
{ \
fprintf(_fp,"[%s]-[%s]-[%s]-[%d] :> "_fmt"\n",_time_str,"INFO",__FILE__,__LINE__,##_X); \
} \
else if(_error_level==DEBUG) \
{ \
fprintf(_fp,"[%s]-[%s]-[%s]-[%d] :> "_fmt"\n",_time_str,"DEBUG",__FILE__,__LINE__,##_X); \
} \
fclose(_fp); \
} \
}while(0);
//函数形式
void log_reocrd(int error_level, const char *format, ...)
{
va_list args;
FILE *fp=NULL;
char time_str[32];
char file_name[256];
va_start (args, format);
time_t time_log = time(NULL);
strftime(file_name,sizeof(file_name),"%Y-%m-%d_log_history.log",localtime(&time_log));
if((fp=fopen(file_name,"a+"))!=NULL)
{
strftime(time_str,sizeof(time_str),"%Y-%m-%d %H:%M:%S",localtime(&time_log));
if(error_level==(int)ERROR)
{
fprintf (fp, "[%s]-[%s]-[%s]-[%d] :> ",time_str,"ERROR",__FILE__,__LINE__);
vfprintf (fp,format,args);
fprintf (fp,"\n");
}
else if(error_level==(int)WARNING)
{
fprintf (fp, "[%s]-[%s]-[%s]-[%d] :> ",time_str,"WARNINGs",__FILE__,__LINE__);
vfprintf (fp,format,args);
fprintf (fp,"\n");
}
else if(error_level==(int)INFO)
{
fprintf (fp, "[%s]-[%s]-[%s]-[%d] :> ",time_str,"INFO",__FILE__,__LINE__);
vfprintf (fp,format,args);
fprintf (fp,"\n");
}
else if(error_level==(int)DEBUG)
{
fprintf (fp, "[%s]-[%s]-[%s]-[%d] :> ",time_str,"DEBUG",__FILE__,__LINE__);
vfprintf (fp,format,args);
fprintf (fp,"\n");
}
fclose(fp);
}
va_end (args);
}
int main()
{
int i=10;
double x=9.123456;
long long k=123456789;
LogRecord(INFO,"i=%d",i)
LogRecord(INFO,"x=%lf",x)
LogRecord(INFO,"k=%lld",k)
LogRecord(INFO,"this is a test")
LogRecord(INFO,"this is a test",NULL)
log_reocrd(INFO,"i=%d",i);
log_reocrd(INFO,"x=%lf",x);
log_reocrd(INFO,"k=%lld",k);
log_reocrd(INFO,"this is a test");
log_reocrd(INFO,"this is a test",NULL);
return 0;
}