一个C实现的记日志的函数库

在实际应用中,日志是一个比较重要的部分。在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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值