嵌入式linux下的c语言简易日志log模块,带颜色显示(一)

时间:2022-07-22
本文章向大家介绍嵌入式linux下的c语言简易日志log模块,带颜色显示(一),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

示例:

Log(DEBUG,"this is debugn"); Log(INFO,"this is infon"); Log(ERROR,"this is errorn"); Log(WARN,"this is warnn");

一个log.c文件和一个log.h文件

使用时包含log.h文件即可。暂时支持四个级别和红绿黄蓝四种颜色,若要增加或扩展,自行更改。

不支持存储日志到文件,以及对日志文件的按日期,按大小等的切割,如有需要,可自行扩展。

计划增加以下内容:

1.增加是否启用日志输出到文件开关,可以选择把日志保存到文件中(写文件属于耗时操作,这块可考虑发送事件或消息给线程去写日志,操做日志的切割)。

2.按日期生成日志文件,可配置保留多少天,超过设定的天数则自动清除超过天数的日志。

3.可增加参数设定限制日志文件的大小,超过限制大小可选择是从头覆盖还是删除重记,还是不在记录。

log.c文件内容:

/**
日志打印示例。
使用:
Log(DEBUG, "This is debug infon");
结果:
[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] = '';
}

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("33[1;32m%s[%s] [%s:%d] %sn33[0m", time, s_loginfo[level], tmp, line, buf);
			break;
		case INFO:
			//蓝色
			printf("33[1;34m%s[%s] [%s:%d] %sn33[0m", time, s_loginfo[level], tmp, line, buf);
			break;
		case ERROR:
			//红色
			printf("33[1;31m%s[%s] [%s:%d] %sn33[0m", time, s_loginfo[level], tmp, line, buf);
			break;
		case WARN:
			//黄色
			printf("33[1;33m%s[%s] [%s:%d] %sn33[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

#