Linux C语言 44-日志记录

2024-01-03 10:26:46

Linux C语言 44-日志记录

本节关键字:Linux、C语言、文件读写、日志记录
相关C库函数:printf、fopen、fprintf、fclose、vsprintf、localtime、

日志记录

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

void WriteLogfile(char *msg, const char *prefile, const char *path)
{
    time_t now = time(0);
    struct tm* curclock = localtime(&now);
    char       filename[128];    
    static int oldwday=-1;

    if (curclock->tm_wday != oldwday && oldwday != -1)
    {
        sprintf(filename, "%s/%d_%s.log", path, curclock->tm_wday, prefile);
        remove(filename);
        oldwday=curclock->tm_wday;
    }
    else
    {
        sprintf(filename, "%s/%d_%s.log", path, curclock->tm_wday, prefile);
    }
    
    int msec;
    struct timeval ttv;
    gettimeofday(&ttv, NULL);
    msec = (ushort)(ttv.tv_usec/1000);

    FILE *fp = fopen(filename, "a+");
    if (!fp) return;
    fprintf(fp,"%.4d-%.2d-%.2d  %.2d:%.2d:%.2d.%.3d  ",
            curclock->tm_year+1900, curclock->tm_mon+1, curclock->tm_mday,
            curclock->tm_hour, curclock->tm_min, curclock->tm_sec, msec);
    fprintf(fp,"%s", msg);
    fclose(fp);
}

void RecordLogs(char *fmt, ...)
{
    char msg[300];
    va_list args;
    va_start(args, fmt);
    vsprintf(msg, fmt, args);
    va_end(args);
    
    WriteLogfile(msg, "debug", "/home/user/log");
}

int main(void)
{
    RecordLogs("this is my first log\n");
    for (int i=10; i<20; i++)
        RecordLogs("%s %dth log\n", "this is my ", i);
    
    return 0;
}

文章来源:https://blog.csdn.net/qq_45157350/article/details/135213872
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。