linux fprintf如何實(shí)現(xiàn)日志輪轉(zhuǎn)

小樊
83
2024-08-27 01:16:25

在Linux中,可以使用logrotate工具實(shí)現(xiàn)日志輪轉(zhuǎn)

  1. 創(chuàng)建一個(gè)日志文件:
#include<stdio.h>
#include <stdarg.h>
#include <time.h>

void write_log(const char *format, ...) {
    FILE *logfile;
    va_list args;
    time_t now;
    char timestr[20];

    logfile = fopen("myapp.log", "a");
    if (logfile == NULL) {
        return;
    }

    time(&now);
    strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", localtime(&now));
    fprintf(logfile, "[%s] ", timestr);

    va_start(args, format);
    vfprintf(logfile, format, args);
    va_end(args);

    fclose(logfile);
}

int main() {
    write_log("This is a log message.\n");
    return 0;
}
  1. 編譯并運(yùn)行程序:
gcc -o myapp myapp.c
./myapp
  1. 創(chuàng)建logrotate配置文件:

/etc/logrotate.d/目錄下創(chuàng)建一個(gè)名為myapp的配置文件。使用文本編輯器打開(kāi)該文件,例如:

sudo nano /etc/logrotate.d/myapp
  1. 編輯logrotate配置文件:

將以下內(nèi)容添加到配置文件中:

/path/to/your/myapp.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
    create 640 root adm
    postrotate
        invoke-rc.d rsyslog rotate > /dev/null
    endscript
}

請(qǐng)確保將/path/to/your/myapp.log替換為實(shí)際的日志文件路徑。

  1. 測(cè)試日志輪轉(zhuǎn):

要測(cè)試日志輪轉(zhuǎn)是否正常工作,可以使用以下命令手動(dòng)運(yùn)行logrotate

sudo logrotate -f /etc/logrotate.d/myapp

這將立即執(zhí)行日志輪轉(zhuǎn)。檢查日志文件是否已按照配置文件中的設(shè)置進(jìn)行了輪轉(zhuǎn)。

現(xiàn)在,每天都會(huì)自動(dòng)進(jìn)行日志輪轉(zhuǎn)。logrotate會(huì)將舊的日志文件壓縮并保留7天。當(dāng)然,你可以根據(jù)需要調(diào)整這些設(shè)置。

0