如何确定是否将新数据写入日志文件以及如何提取这些新数据并将其写入另一个文件?
我的目标是创build一个大日志文件用于debugging目的,因为当前日志文件总是删除数据,如果文件达到特定的大小。
我唯一的想法是每隔几分钟从旧的日志文件创build一个副本。
快速和肮脏的方法是在您的控制台中键入以下行 – 用实际路径和日志文件替换“路径/到/ …”和“其他/路径/ …”:
* * * * * /path/to/small_file.log >> /other/path/to/big_file.log
它不会每写一次都执行IO,但它会每分钟执行一次,这可能会或可能不足以满足您的需求。
编辑:试图找到一个更好的方法使用C,这是我到目前为止(阅读我的评论,在岗位了解更多信息)。
//Include the full pathname and file for LOG_BIG and LOG_SMALL #define LOG_BIG "/var/.../log_example_big.txt" #define LOG_SMALL "/var/.../log_example_small.txt" //FIXME: change LOG_BIG and LOG_SMALL to match the locations of the logfiles #include <time.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <math.h> #include <sys/types.h> time_t last_mod_time(const char *path); int main(int argc, const char * argv[]) { char outstr[200]; time_t t; struct tm *tmp; t = time(NULL); tmp = localtime(&t); // check for local time set failure if (tmp == NULL) { perror("localtime"); return 0; } //if the returned size_t for strftime is 0, we exit if (strftime(outstr, sizeof(outstr), argv[1], tmp) == 0) { fprintf(stderr, "strftime returned 0"); return 0; } double diff_log_mod_time; // get the difference of last modified time between LOG_BIG and LOG_SMALL diff_log_mod_time = difftime(last_mod_time(LOG_BIG),last_mod_time(LOG_SMALL)); //difference in log modification times should be close to 0 +/- 10 ... I think if(fabs(diff_log_mod_time) > 10.0) { /* to finish the code, we would need to find the difference between the data in LOG_BIG and LOG_SMALL (assuming that LOG_BIG should contain all of LOG_SMALL and then some) */ } exit(EXIT_SUCCESS); } /** * last_mod_time - this function finds the last modification time for a filename specified and returns * it in epoch time (seconds lapsed since 1/1/1970) */ time_t last_mod_time(const char *path) { struct stat statbuf; if (stat(path, &statbuf) == -1) { perror(path); exit(1); } return statbuf.st_mtime; }
另一个快速和肮脏的方法来实现这一点将是做到以下几点:
cp /path/to/small_file.log /other/path/to/big_file.log; nohup tail -f /path/to/small_file.log >> /other/path/to/big_file.log &