C语言开发—日志&测试框架
头文件log.h
#ifndef _EM_LOG_H_
#define _EM_LOG_H_
#include <stdio.h>
#include <stdarg.h>
#define OPEN_LOG 1 //日志开关
#define LOG_LEVEL LOG_DEBUG //日志等级
#define LOG_SAVE 1
/*
*日志等级
*/
typedef enum
{
LOG_DEBUG = 0,
LOG_INFO,
LOG_WARN,
LOG_ERROR,
} E_LOGLEVEL;
void EM_LOG(const int level,const char* fun,const int line,const char *fmt, ...);
#define EMLog(level,fmt...) EM_LOG(level,__FUNCTION__,__LINE__,fmt)
#endif
实现代码log.c
#include "log.h"
/*
*获取日志名称
*/
char *EM_LOGLevelGet(const int level)
{
switch (level)
{
case LOG_DEBUG:
return "DEBUG";
break;
case LOG_INFO:
return "INFO";
break;
case LOG_WARN:
return "WARN";
break;
case LOG_ERROR:
return "ERROR";
break;
default:
return "UNKNOWN";
break;
}
}
/*
*打印日志
*/
void EM_LOG(const int level,const char* fun,const int line,const char *fmt, ...)
{
#ifdef OPEN_LOG
va_list arg;
va_start(arg, fmt);
char buf[1 + vsnprintf(NULL, 0, fmt, arg)];
vsnprintf(buf, sizeof(buf), fmt, arg);
va_end(arg);
if (level >= LOG_LEVEL)
printf("[%s] [%s %d]%s\n", EM_LOGLevelGet(level),fun,line,buf);
//TODO 存储
#endif
}
测试调用
#include <stdio.h>
#include "log.h"
void main()
{
int a = 1, b = 2, c = 3;
EMLog(LOG_DEBUG, "app start");
EMLog(LOG_INFO, "A = %d B = %d C = %d", a, b, c);
EMLog(LOG_WARN, "app warn");
EMLog(LOG_DEBUG, "app start");
}
google测试框架
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int output;
int a;
int b;
int (*TestEMFunc)(int, int);
/* data */
} T_EMTest;
T_EMTest *addFunc(int (*TestEMFunc)(int, int), int a, int b, int output)
{
T_EMTest *m_EMTest = (T_EMTest *)malloc(sizeof(T_EMTest));
m_EMTest->a = a;
m_EMTest->b = b;
m_EMTest->TestEMFunc = TestEMFunc;
m_EMTest->output = output;
return m_EMTest;
}
void runEMTest(T_EMTest *p_EMTest){
if(p_EMTest != NULL){
int count = p_EMTest->TestEMFunc(p_EMTest->a,p_EMTest->b);
if(count == p_EMTest->output){
printf("success \n");
}
else{
printf("fail %d != %d",count,p_EMTest->output);
}
free(p_EMTest);
}
}
int add(int a, int b)
{
// TODO
return a + b;
}
void main()
{
printf("app start \n");
T_EMTest *m_EMTest = addFunc(add,1,2,5);
runEMTest(m_EMTest);
}