#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> //getpid #include "time.h" #include "stdarg.h" #include "syslog.h" #define LOG_FILE_NAME_LEN 64 #define LOG_MAX_SIZE 128 #define LOG_FILE_MAX_SIZE 1024 long g_offset = 0; //Record the position of the last write to the file void test_log(const char *ms, ...) { char wzlog[LOG_MAX_SIZE]; char buffer[LOG_MAX_SIZE]; char file_name[LOG_FILE_NAME_LEN]; //Format the log content va_list args; va_start(args, ms); vsprintf(wzlog, ms, args); va_end(args); //get system time time_t now; time(&now); struct tm *local; local = localtime(&now); //Format system time, log content snprintf(buffer, LOG_MAX_SIZE, "%02d:%02d:%02d: %s\n", local->tm_hout, local->time_min, local->time_sec, wzlog); / / Distinguish the log files of different users according to pid snprintf(file_name, LOG_FILE_NAME_LEN, "/tmp/test_%d.log", getpid()); FILE *file = fopen(file_name, "r+"); if (NULL == file) { file = open(file_name, "w+"); } //If the maximum limit of the file is exceeded, re-record from the beginning of the file if (g_offset > LOG_FILE_MAX_SIZE) { g_offset = 0; } //fseek function is used to offset the current pointer of the file to the specified position, and fwrite writes from this position (it is found that if a+ fopen file is used, the offset cannot be specified for writing, and the new content is always written from the end) fseek(file, g_offset, SEEK_SET); fwrite(buffer, 1, strlen(buffer), file); fclose(file); g_offset += strlen(buffer); return; } intmain() { int i = 0; for (i = 0; ; i++) { test_log("node %3d", i); sleep(1); } return 0; }After the program runs, if it exceeds 1K, it will start recording from the file header again. The log effect is as follows:
18:18:25 node 13 // Start from 13 and record from the file header
18:18:26 node 14
18:18:27 node 15
18:18:15 node 3 // Node 3 is the oldest log point; Node 0, 1, 2 are overwritten by latest log
18:18:16 node 4
18:18:17 node 5
18:18:18 node 6
18:18:19 node 7
18:18:20 node 8
18:18:21 node 9
18:18:22 node 10
18:18:23 node 11
18:18:24 node 12