C語言實現日志封裝


 一、文件操作

見鏈接 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM