首页 > 技术文章 > C语言实现日志封装

macrored 2019-09-04 11:34 原文

 一、文件操作

见链接 https://www.cnblogs.com/dolphin0520/archive/2011/10/05/2199598.html

二、系统时间

见链接 https://blog.csdn.net/u012229282/article/details/79598287

三、日志封装实现

简单版本,不带时间戳:

#include <stdio.h>
#define LOG(level, format, ...) \
        fprintf(stderr, "[%s|%s@%s:%d] " format "\n", \
            level, __func__, __FILE__, __LINE__, ##__VA_ARGS__ )

函数版本:

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

void logC(const char *func, const char *file, const int line,
          const char *type, const char *format, ...)
{
    FILE *file_fp;
    time_t loacl_time;
    char time_str[128];

    // 获取本地时间
    time(&loacl_time);
    strftime(time_str, sizeof(time_str), "[%Y.%m.%d %X]", localtime(&loacl_time));
    
    // 日志内容格式转换
    va_list ap;
    va_start(ap, format);
    char fmt_str[2048];
    vsnprintf(fmt_str, sizeof(fmt_str), format, ap);
    va_end(ap);

    // 打开日志文件
    file_fp = fopen("./main.log", "a");
    
    // 写入到日志文件中
    if (file_fp != NULL)
    {
        fprintf(file_fp, "[%s]%s[%s@%s:%d] %s\n", type, time_str, func, 
                file, line, fmt_str);
        fclose(file_fp);
    }
    else
    {
        fprintf(stderr, "[%s]%s[%s@%s:%d] %s\n", type, time_str, func, 
                file, line, fmt_str);
    }
}

#define LOGC(type, format, ...) logC(__func__, __FILE__, __LINE__, type, format, ##__VA_ARGS__)

四、实现效果

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

void logC(const char *func, const char *file, const int line,
          const char *type, const char *format, ...)
{
    FILE *file_fp;
    time_t loacl_time;
    char time_str[128];

    // 获取本地时间
    time(&loacl_time);
    strftime(time_str, sizeof(time_str), "[%Y.%m.%d %X]", localtime(&loacl_time));
    
    // 日志内容格式转换
    va_list ap;
    va_start(ap, format);
    char fmt_str[2048];
    vsnprintf(fmt_str, sizeof(fmt_str), format, ap);
    va_end(ap);

    // 打开日志文件
    file_fp = fopen("./main.log", "a");
    
    // 写入到日志文件中
    if (file_fp != NULL)
    {
        fprintf(file_fp, "[%s]%s[%s@%s:%d] %s\n", type, time_str, func, 
                file, line, fmt_str);
        fclose(file_fp);
    }
    else
    {
        fprintf(stderr, "[%s]%s[%s@%s:%d] %s\n", type, time_str, func, 
                file, line, fmt_str);
    }
}

#define LOGC(type, format, ...) logC(__func__, __FILE__, __LINE__, type, format, ##__VA_ARGS__)

int main()
{
    LOGC("LOG_DEBUG", "a=%d", 10);
    return 0;
}

日志函数内容输出如下:

macrored@ubuntu:~/Desktop$ cat test.log
[LOG_DEBUG][2019.01.01 01:01:01|main@test.c:20] a=10

参考链接 https://blog.csdn.net/shanzhizi/article/details/8983768

推荐阅读