在一个项目中需要使用日志记录,网上也有很多开源代码,自己也尝试着写了一个!异步日志系统正在进行中。
//mylog.h 头文件
#ifndef _MYLOG_HEADER_
#define _MYLOG_HEADER_
#ifdef __cpluscplus
extern "C"{
#endif
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <error.h>
#define LOG_MAX_FILE_NAME (64)
#define LOG_MAX_OUTPUT_NAME (128)
#define LOG_TIME_STR_LEN (21)
#define MAX_FILE_COUNT (50)
#define MAX_FILE_SIZE (1024*1024*3)
/****************
每一个文件对于一个这样的结构体
,不管是多线程写还是单线程
都是对应一个描述文件的结构体
****************************/
typedef struct _log_file_t_
{
FILE *fp; //文件指针
unsigned char filename[LOG_MAX_FILE_NAME];//输入文件的名字
unsigned char output_filename[LOG_MAX_OUTPUT_NAME];//输出文件的名字
unsigned int filesize;// 当前文件的大小
unsigned int active_count;//写文件的线程数
}log_file_t;
typedef struct _log_t
{
pthread_key_t key;
pthread_mutex_t mutex;
unsigned int roll_size;
unsigned int max_filesize;
log_file_t *file_count[MAX_FILE_COUNT];
unsigned char last_time_str[LOG_TIME_STR_LEN+1];
unsigned int file_index;
}f_log;
char* _log_create_filename(char* filename,char* output_filename);
#ifdef __cpluscplus
}
#endif
#endif
函数实现:
#include "mylog.h"
static f_log* g_log = NULL;
static pthread_once_t init_create = PTHREAD_ONCE_INIT;
/*********************
内部函数实现
********************/
// 全局变量 初始化
static void _log_init()
{
int i;
f_log *temp_glo=NULL;
temp_glo = (f_log*)malloc(sizeof(f_log));
if(temp_glo == NULL)
{
printf("Can not malloc f_log!!!\r\n");
return ;
}
pthread_mutex_init(&temp_glo->mute