在实际应用中,日志是一个比较重要的部分。在unix下用得比较多的是syslog之类的机制。但是我感觉不是很方便,于是编写了下面这个日志函数库。支持分级,同时支持不重启应用而开关日志。
/*
logc.c
by towerjt
*/
#include <logc.h>
static char log_config_path[64];
static char current_date[11];
static char current_time[9];
static const char* const priorities[PRIORITY_NUM] = {
"FATAL",
"ERROR",
"WARN",
"INFO",
"DEBUG"
};
static void getConfig(char *subject)
{
char *p;
memset(log_config_path,0,sizeof(log_config_path));
if ( ( p = getenv("XLOG_CONFIG_PATH") ))
strncpy(log_config_path,p,sizeof(log_config_path));
else
strcpy(log_config_path,DEFAULT_CONFIG);
}
static void getTime()
{
struct tm* m;
time_t g_t;
g_t = time(NULL);
m = localtime(&g_t);
sprintf(current_date,"%d-%02d-%02d",
m->tm_year+1900,
m->tm_mon+1,
m->tm_mday
);
sprintf(current_time,"%02d:%02d:%02d",
m->tm_hour,
m->tm_min,
m->tm_sec
);
}
static int getPriority(char *subject,int p_level)
{
struct stat buf;
char p_name[128];
snprintf(p_name, sizeof(p_name), "%s/%s.%s",
log_config_path,
subject,
priorities[p_level-1]);
return stat(p_name, &buf);
}
void logc_out(char *subject,int priority_level,char *fmt,...)
{
int i;
FILE *f1;
char fname[128];
va_list args;
getConfig(subject);
getTime();
if ( ! getPriority(subject,priority_level) )
{
sprintf(fname,"%s/%s_%s_%s.log",log_config_path,
subject,
priorities[priority_level-1],
current_date);
f1 = fopen(fname,"a");
if (f1)
{
fprintf(f1,"[%d]%s %s @ ",getpid(),current_date,current_time);
va_start(args, fmt);
vfprintf(f1,fmt,args);
va_end(args);
fclose(f1);
}
}
}
/*
logc.c
by towerjt
*/
#ifndef __logc__
#define __logc__
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#define DEFAULT_CONFIG "/work02/log"
#define PRIORITY_NUM 5
#define P_FATAL 1
#define P_ERROR 2
#define P_WARN 3
#define P_INFO 4
#define P_DEBUG 5
void logc_out(char *subject,int priority_level,char *fmt,...);
#endif