日誌記錄方法

/*
 * =====================================================================================
 *
 *       Filename:  err_log.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2011年07月19日 10時21分05秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  sunsea (zsx), [email protected]
 *        Company:  
 *
 * =====================================================================================
 */

#include <stdio.h>
#include <string.h> 
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define	LOG_BASE_DIR	"."
#define	MAX_LOG_SIZE	200 * 1024	//200KB

int err_log(const char *log_msg, int err_no, const char *trace_file, int line_no)
{
	FILE	*fp = NULL;
	char	log_file[256];
	char	time_str[128];
	int	fildes = 0;
	time_t	tv;
	struct	tm *lc_time;
	struct	stat fs_buf;

	memset(log_file, 0, sizeof(log_file));
	sprintf(log_file, "%s/err_log.txt", LOG_BASE_DIR);

	tv = time(NULL);
	lc_time = localtime(&tv);
	memset(time_str, 0, sizeof(time_str));
//	strcpy(time_str, asctime(lc_time));
	sprintf(time_str, "%d-%02d-%02d %02d:%02d:%02d",\
			lc_time->tm_year + 1900, lc_time->tm_mon + 1, lc_time->tm_mday,\
			lc_time->tm_hour, lc_time->tm_min, lc_time->tm_sec);

	fildes = open(log_file, O_RDONLY);
	memset(&fs_buf, 0, sizeof(fs_buf));
	fstat(fildes, &fs_buf);
	close(fildes);

	if (fs_buf.st_size < MAX_LOG_SIZE)
	{
		fp = fopen(log_file, "a");
	}
	else
	{
		fp = fopen(log_file, "w");
	}

	if (NULL == fp)
	{
		printf("Error: open %s error!\n", log_file);

		return -1;
	}

	fprintf(fp, "%s [%d] %s [%s (%d)]\n", time_str, err_no, log_msg, trace_file, line_no);

	fclose(fp);

	return 0; 
}

int main(int argc, char* argv[])
{
	err_log("This is a error!", 1, __FILE__, __LINE__);

	return 0; 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章