0
点赞
收藏
分享

微信扫一扫

C语言实现的简易日志log库,带颜色显示


C语言实现的简易日志log库,带颜色显示_#include

log.c文件

/**
日志打印示例。
使用:
Log(DEBUG, "This is debug info\n");
结果:
[2018-07-22 23:37:27:172] [DEBUG] [main.cpp:5] This is debug info
默认打印当前时间(精确到毫秒)、文件名称、行号。
*/
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>

#include "log.h"

#ifndef LOGLEVEL
#define LOGLEVEL DEBUG
#endif

// 使用了GNU C扩展语法,只在gcc(C语言)生效,
// g++的c++版本编译不通过
static const char* s_loginfo[] = {
[ERROR] = "ERROR",
[WARN] = "WARN",
[INFO] = "INFO",
[DEBUG] = "DEBUG",
};

static void get_timestamp(char *buffer)
{
time_t t;
struct tm *p;
struct timeval tv;
int len;
int millsec;

t = time(NULL);
p = localtime(&t);

gettimeofday(&tv, NULL);
millsec = (int)(tv.tv_usec / 1000);

/* 时间格式:[2011-11-15 12:47:34:888] */
len = snprintf(buffer, 32, "[%04d-%02d-%02d %02d:%02d:%02d:%03d] ",
p->tm_year+1900, p->tm_mon+1,
p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, millsec);

buffer[len] = '\0';
}

void mylog1(const char* filename, int line, enum LogLevel level, const char* fmt, ...)
{
if(level > LOGLEVEL)
return;

va_list arg_list;
char buf[1024];
memset(buf, 0, 1024);
va_start(arg_list, fmt);
vsnprintf(buf, 1024, fmt, arg_list);
char time[32] = {0};

// 去掉*可能*存在的目录路径,只保留文件名
const char* tmp = strrchr(filename, '/');
if (!tmp) tmp = filename;
else tmp++;
get_timestamp(time);

switch(level){
case DEBUG:
//绿色
printf("\033[1;32m%s[%s] [%s:%d] %s\n\033[0m", time, s_loginfo[level], tmp, line, buf);
break;
case INFO:
//蓝色
printf("\033[1;34m%s[%s] [%s:%d] %s\n\033[0m", time, s_loginfo[level], tmp, line, buf);
break;
case ERROR:
//红色
printf("\033[1;31m%s[%s] [%s:%d] %s\n\033[0m", time, s_loginfo[level], tmp, line, buf);
break;
case WARN:
//黄色
printf("\033[1;33m%s[%s] [%s:%d] %s\n\033[0m", time, s_loginfo[level], tmp, line, buf);
break;
}
va_end(arg_list);
}

log.h文件

#ifndef LOG_H_
#define LOG_H_

#ifdef __cplusplus
extern "C" {
#endif

enum LogLevel
{
ERROR = 1,
WARN = 2,
INFO = 3,
DEBUG = 4,
};

void mylog1(const char* filename, int line, enum LogLevel level, const char* fmt, ...) __attribute__((format(printf,4,5)));

#define Log(level, format, ...) mylog1(__FILE__, __LINE__, level, format, ## __VA_ARGS__)

#ifdef __cplusplus
};
#endif

#endif

实际调用main.c:

#include "stdio.h"
#include "stdlib.h"
#include "log.h"

int main(void)
{
Log(DEBUG,"this is debug %d-%x-%.2f", 100, 200, 1.234);
Log(INFO,"this is info %d-%x-%.2f", 100, 200, 1.234);
Log(ERROR,"this is error %d-%x-%.2f", 100, 200, 1.234);
Log(WARN,"this is warn %d-%x-%.2f", 100, 200, 1.234);

return 0;
}

输出效果:

C语言实现的简易日志log库,带颜色显示_#include



举报

相关推荐

0 条评论