Ubuntu/linux 下C语言实现日志接口
纯代码
/* 日志接口 */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <stdbool.h>
#include <time.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#define LOG_PATH "/var/log/sys_daemon.log" /* 本程序的日志路径 */
void log_info(const char *format, ...) {
char time_str[128] = {0};
char log_str[256] = {0};
char sys_str[256] = {0};
int size;
struct stat sta;
stat(LOG_PATH, &sta); //获取日志文件信息
size = sta.st_size; //获取信息中的文件大小单位字节
if (size > 1024 * 1024 * 10) { //判断日志过大时清空
sprintf(sys_str, ">%s", LOG_PATH);
} else {
printf("log size is %d", size);
}
time_t rawtime;
struct tm *local_time;
va_list parg;
va_start(parg, format);
vsnprintf(log_str, 256, format, parg);
time((time_t *)&rawtime);
local_time = localtime( &rawtime );
strftime(time_str, 128, "%Y-%m-%d %H:%M:%S", local_time); //获取格式化的日志时间
sprintf(sys_str, "echo \"%s %s\">>%s", time_str, log_str, LOG_PATH);
system(sys_str);
/*log_fp = fopen(LOG_PATH, "a"); //多线程不安全的 容易造成double close然后段错误
if (log_fp != NULL) {
fprintf(log_fp, "%s | %s\n", time_str, log_str);
fclose(log_fp);
} else {
fprintf(stderr, "[sys_error] %s | open log file failed!\n", time_str);
}
*/
}