02_实战项目Zlog日志框架
Zlog日志
注释控制日志打印
//printf("app start\n");
printf("app start\n");
printf("app start\n");
//printf("app start\n");
printf("app start\n");
//printf("app start\n");
printf("app start\n");
特点: 麻烦,产品发布时要注释所有日志, 开发时要打开日志
define 控制日志打印
#include <stdio.h>
// #define OPEN_LOG 1
int main(int argc, char const *argv[])
{
#ifdef OPEN_LOG
printf("app start\n");
#endif
printf("constant.\n");
#ifdef OPEN_LOG
printf("app start\n");
#endif
return 0;
}
特点: 比注释高效, 但每次打印日志都需要加#ifdef OPEN_LOG和#endif
日志打印工具文件
log.c
#include "log.h"
char *EM_LOGLevelGet(const int level)
{
switch (level)
{
case LOG_DEBUG:
return "DEBUG";
case LOG_INFO:
return "INFO";
case LOG_WARN:
return "WARN";
case LOG_ERROR:
return "ERROR";
default:
return "UNKNOW";
}
}
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[vsnprintf(NULL, 0, fmt, arg)];
vsnprintf(buf, sizeof(buf) + 1, fmt, arg);
va_end(arg);
if (level >= LOG_LEVEL)
{
printf("[%s] [%s %d] %s\n", EM_LOGLevelGet(level), fun, line, buf);
}
#endif
}
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
typedef enum
{
LOG_DEBUG = 0,
LOG_INFO,
LOG_WARN,
LOG_ERROR,
} E_LOGLEVEL;
extern 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
调用日志文件
#include<stdio.h>
#include"log.h"
int main(int argc, char const *argv[])
{
int a = 10, b = 11;
// EM_LOG(LOG_DEBUG, "app LOG_DEBUG");
// EM_LOG(LOG_INFO, "A = %d", a);
// EM_LOG(LOG_WARN, "app LOG_WARN");
// EM_LOG(LOG_ERROR, "app LOG_ERROR");
EMLog(LOG_DEBUG, "app_start");
return 0;
}