在Linux中,可以使用logrotate
工具實(shí)現(xiàn)日志輪轉(zhuǎn)
#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;
}
gcc -o myapp myapp.c
./myapp
logrotate
配置文件:在/etc/logrotate.d/
目錄下創(chuàng)建一個(gè)名為myapp
的配置文件。使用文本編輯器打開(kāi)該文件,例如:
sudo nano /etc/logrotate.d/myapp
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í)際的日志文件路徑。
要測(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è)置。