您的位置:首页 > 编程语言 > C语言/C++

通过宏定义的日志插件-C语言

2016-07-20 16:46 459 查看
服务器程序运行少不了日志文件的输出,joyyzhang Google了一下相关的插件,发现实现的都太复杂,用起来也不方便,于是joyyzhang通过宏定义实现了一个轻量级的日志插件,只需引用其头文件即可使用,还能自定义日志的级别,用起来十分方便。

头文件代码如下.

#include <stdio.h>
#include <time.h>
#include <string.h>

#ifndef LOG_PARA
#define LOG_PARA
FILE *log_file = NULL;
const char *LOG_FILE = "logfile";
const char LEVEL[3][20] = {"DEBUG","INFO","ERROR"};
const int CURRENT_LEVEL = 1;
const int PRINT_INFO = 1;
#define LOG_ON 1
#endif

#if LOG_ON
#define LogWrite(level,s,arg...)\
if(PRINT_INFO){fprintf(stdout,s,##arg);printf("\n");}\
if(level >= CURRENT_LEVEL)\
{log_file = fopen(LOG_FILE,"a");\
fprintf(log_file,GET_MSG(level,s),##arg);\
fflush(log_file);fclose(log_file);}
#else
#define LogWrite(level,f DMC_DEBUGs,arg...)
#endif

char *GET_MSG(int level,std::string s){
static char log_msg[1000];
time_t t = time(0);
struct tm *local = localtime(&t);
char time_buf[128];
strftime(time_buf,64,"%Y/%m/%d %H:%M:%S",local);
strcpy(log_msg,"[");
strcat(log_msg,time_buf);
strcat(log_msg,"] [");
strcat(log_msg,LEVEL[level]);
strcat(log_msg,"] ");
strcat(log_msg,s.c_str());
strcat(log_msg,"\n");
return log_msg;
}

void LogClear(){
log_file = fopen(LOG_FILE,"w");
fclose(log_file);
}

/*
void test(){
LogWrite(0,"%d\n",123);
LogClear();
return;
}
*/


将该文件命名为log.h,放在源码的同级目录下

要用到日志的代码在其头部加上

#include "log.h"


即可使用,具体用法见test()函数,与printf语法基本一样,还加上了加了日志级别的判定。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  插件