c语言编程基础之日志记录

#include <unistd.h>
#include <time.h>
#include <sys/signal.h>
#include <sys/stat.h>
#include<stdio.h>
#include<varargs.h>
#include<stdarg.h>
#define cgDebug 2    //日志级别 3 debug 2 info 1 warn 0 error
#define agDebugfile "mylog.log"

/**
***将time()函数取得的秒数转成具体日期时间.
***参数datetime是传进的time()函数取得的秒数
***返回时间格式为YYYY/MM/DD-hh:mm:ss的字符串
**/
char * changeDt(long *datetime)
{
  struct tm *T;
  char buf[101],temp[5];

  T=localtime(datetime);

  sprintf(buf,"%d/",T->tm_year+1900);
  if(T->tm_mon+1<10)
	strcat(buf,"0");
  memset(temp,0x00,sizeof(temp));
  sprintf(temp,"%d/",T->tm_mon+1);
  strcat(buf,temp);
  if(T->tm_mday<10)
	strcat(buf,"0");
  memset(temp,0x00,sizeof(temp));
  sprintf(temp,"%d-",T->tm_mday);
  strcat(buf,temp);
  if(T->tm_hour<10)
	strcat(buf,"0");
  memset(temp,0x00,sizeof(temp));
  sprintf(temp,"%d:",T->tm_hour);
  strcat(buf,temp);
  if(T->tm_min<10)
	strcat(buf,"0");
  memset(temp,0x00,sizeof(temp));
  sprintf(temp,"%d:",T->tm_min);
  strcat(buf,temp);
  if(T->tm_sec<10)
	strcat(buf,"0");
  memset(temp,0x00,sizeof(temp));
  sprintf(temp,"%d",T->tm_sec);
  strcat(buf,temp);

  return(buf);
}

/**
***取系统日期和时间
**/
int GetDt(char *dt)
{
  long datetime;
  time( &datetime );
  strcpy(dt,changeDt(&datetime));
  return 0;
}

/**
***打印日志,iDebug是打印级别,成功返回0,失败返回-1
**/
int TraceLog(iDebug, saFileName, iLine, frm, va_alist)
short iDebug;
char *saFileName;
int	iLine;
char *frm;
va_dcl
{
  static short ilTrace_flag = 0;
  static long llLogfilesize = 0;
  FILE *fp;
  char buf[2048],fname1[100],buf1[2048],alCmdbuf[200];
  va_list  ap;
  struct tm  *sttm;
  int ilRc;
  long llDatetime;
  short ilRn;
  struct stat sgbuf;
  int rc;
  char buf2[256];

  if ( cgDebug < iDebug ) return(0);
  signal(SIGTTOU,SIG_IGN);
  
  memset(buf,0x00,sizeof(buf));
  memset(buf1,0x00,sizeof(buf1));
  memset(fname1,0x00,sizeof(fname1));
  if (*frm) 
  {
    va_start(ap);
    vsprintf(buf, frm, ap);
    va_end(ap);
  }
  /* 自动清空大于 8M 文件*/
  llLogfilesize = 8388608L;

  sprintf(fname1,"%s/item/zhlx/log/%s",getenv("HOME"),agDebugfile);
  rc=stat(fname1, &sgbuf);
  if (sgbuf.st_size > llLogfilesize)
  {
    time(&llDatetime);
    sttm = localtime( &llDatetime );

    sprintf(alCmdbuf,"mv %s %s.%02d%02d%02d%02d%02d",
      fname1,fname1,
      sttm->tm_mon+1,
      sttm->tm_mday,
      sttm->tm_hour,
      sttm->tm_min,
      sttm->tm_sec );
    if ((access(fname1,F_OK)) != -1)
      system(alCmdbuf);
  }
  if (( fp = fopen(fname1,"a+")) == NULL)  
     {
        printf("打开日志文件出错\n");
	return(-1);
     }
  GetDt(buf1);
  sprintf(buf2, " % 10s->% 4d ", saFileName, iLine);
  strcat(buf1,buf2);
  strcat(buf1,buf);
  fprintf(fp,"%s\n",buf1 + 5);
  fclose(fp);
  return(0);
}

main()
{
  TraceLog(3,__FILE__, __LINE__,"debug测试信息");
  TraceLog(2,__FILE__, __LINE__,"info测试信息");
  TraceLog(1,__FILE__, __LINE__,"warn测试信息");
  TraceLog(0,__FILE__, __LINE__,"error测试信息");
}

你可能感兴趣的:(编程,C++,c,C#,D语言)