C/C++ 打印日志到文件

本文档详细介绍了如何在C++中使用C/C++编程语言创建一个简单的日志模块,包括初始化、打印日志到文件以及关闭文件的操作。通过LogPrint.cpp示例代码,读者可以了解到如何使用fprintf和va_list进行格式化打印,并附带了编译和运行结果。
摘要由CSDN通过智能技术生成

1. C/C++ 打印日志到文件示例代码

// LogPrint.cpp
#include <stdio.h>
#include <unistd.h>
#include <stdarg.h>
#include <string.h>
#include <fcntl.h>
#include <time.h>

#define MAX_LEN 1024
#define LOG_FILE "./Test.log"

FILE *fd_log = nullptr;

int Log_Init()
{
    int ret = -1;
    if( (fd_log = fopen(LOG_FILE, "a+")) == nullptr)
    {
        printf("open file failed!\n");
    }
    else {
        printf("open file successed!\n");
        ret = 0;
    }
    return ret;
}

void Log_End()
{
    fclose(fd_log);
}

// 使用方法同 printf
void Log_Printf(const char *fmt, ...)
{
    static bool print_time = true; //是否要打印时间: 当 debug_mode 为真,且上一次是换行符结尾。
    char message[MAX_LEN];

    // 当前时间.
    time_t timer = time(NULL);
    strftime(message, 24, "\n[%Y-%m-%d %H:%M:%S] ", localtime(&timer));
    va_list args;
    va_start(args, fmt);
    vsnprintf(message + 23, MAX_LEN - 23, fmt, args);
    va_end(args);

    printf("%s\n", message + 23);


    if (fwrite(message, strlen(message), 1, fd_log) != 1)
    {
            perror("lprintf");
    }
}

int main()
{
    printf("Begin -------------\n");
    Log_Init();
    Log_Printf("sssssssssssssssssssssssss2");
    Log_Printf("222222222222222222222222222");
    Log_Printf("122485444444444444444");
    Log_End();
    printf("End -------------\n");
}

2. 编译命令

g++ -std=c++17 LogPrint.cpp -o LogPrint

3. 运行结果

X:~/TestCode$ ./LogPrint 
Begin -------------
open file successed!
sssssssssssssssssssssssss2
222222222222222222222222222
122485444444444444444
End -------------


X:~/TestCode$ cat Test.log 

[2021-12-09 14:16:49] sssssssssssssssssssssssss2
[2021-12-09 14:16:49] 222222222222222222222222222
[2021-12-09 14:16:49] 122485444444444444444

4. 参考连接

打印并输出 log/日志到文件(C++)_mb60f8ef05632b9_51CTO博客

以下是一个简单的C++实现,使用了哈希表和双端队列来存储相似日志和相同日志的时间戳。 ```c++ #include <iostream> <string> #include <unordered_map> #include <deque> #include <chrono> using namespace std; // 定义日志抑制的时间阈值 const int SAME_LOG_THRESHOLD = 10; // 单位:ms const int SIMILAR_LOG_THRESHOLD = 100; // 单位:ms // 哈希表存储相似日志的时间戳 unordered_map<string, deque<long long>> similar_logs; // 哈希表存储相同日志的时间戳 unordered_map<string, long long> same_logs; // 判断两个日志是否相似 bool isSimilar(const string& log1, const string& log2) { // 去除数字后比较 string s1, s2; for (char c : log1) { if (!isdigit(c)) s1 += c; } for (char c : log2) { if (!isdigit(c)) s2 += c; } return s1 == s2; } // 处理日志 void processLog(const string& log) { auto now = chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch()).count(); // 处理相似日志 if (similar_logs.count(log)) { // 如果相似日志队列为空或者时间差大于阈值,则将当前日志的时间戳插入队列 if (similar_logs[log].empty() || now - similar_logs[log].back() > SIMILAR_LOG_THRESHOLD) { similar_logs[log].push_back(now); } // 如果队列长度超过10,则抑制当前日志 if (similar_logs[log].size() > 9) { return; } } else { // 如果当前日志不相似,则清空相似日志队列 for (auto it = similar_logs.begin(); it != similar_logs.end(); ) { if (isSimilar(log, it->first)) { it = similar_logs.erase(it); } else { ++it; } } // 插入当前日志的时间戳 similar_logs[log].push_back(now); } // 处理相同日志 if (same_logs.count(log)) { // 如果时间差小于阈值,则抑制当前日志 if (now - same_logs[log] < SAME_LOG_THRESHOLD) { return; } } // 更新相同日志的时间戳 same_logs[log] = now; // 输出当前日志 cout << log << endl; } int main() { string log; while (getline(cin, log)) { processLog(log); } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值