1、日志初始化创建
2、日志写入
3、日志关闭
log.c
#include "log.h"
static log_t LOG;
//初始化日志文件,在当前目录创建日志文件
int log_init(char *pdirname)
{
time_t t;
struct tm *ptm = NULL;
char filepath[64] = {0};
int ret = 0;
time(&t);
ptm = localtime(&t);
ret = access(pdirname, F_OK);
if (0 != ret)
{
mkdir(pdirname, 0777);
}
sprintf(filepath, "%s/log_%4d%02d%02d", pdirname, ptm->tm_year+1900, ptm->tm_mon+1, ptm->tm_mday);
LOG.flog = fopen(filepath, "a");
if (NULL == LOG.flog)
{
fprintf(stderr, "logfile open faileed, can not record software information");
return -1;
}
LOG.curtime = ptm;
pthread_mutex_init(&LOG.lock, NULL);
return 0;
}
//写入日志文件
int log_write(LEVEL_T level,const char *pfile, const int line, const char *pfunc, const char *pstr, ...)
{
time_t t;
struct tm *ptm = NULL;
char tmpinfo[1024] = {0};
va_list pnext;
pthread_mutex_lock(&LOG.lock);
if (level < LOG.curlevel)
{
pthread_mutex_unlock(&LOG.lock);
return 0;
}
va_start(pnext, pstr);
time(&t);
ptm = localtime(&t);
if (ptm->tm_year != LOG.curtime->tm_year | ptm->tm_mon != LOG.curtime->tm_mon | ptm->tm_mday != LOG.curtime->tm_mday)
{
pthread_mutex_unlock(&LOG.lock);
log_deinit();
log_init("LOG_FILE");
pthread_mutex_lock(&LOG.lock);
LOG.curtime = ptm;
}
sprintf(tmpinfo, "%s\n", pstr);
fprintf(LOG.flog, "[%4d-%02d-%02d %02d-%02d-%02d] [%s %d %s] ", ptm->tm_year+1900, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec, pfile, line, pfunc);
vfprintf(LOG.flog, tmpinfo, pnext);
va_end(pnext);
pthread_mutex_unlock(&LOG.lock);
return 0;
}
//销毁日志文件
int log_deinit(void)
{
//关闭日志文件
if (NULL != LOG.flog)
{
pthread_mutex_lock(&LOG.lock);
fclose(LOG.flog);
LOG.flog = NULL;
pthread_mutex_unlock(&LOG.lock);
pthread_mutex_destroy(&LOG.lock);
}
return 0;
}
//设置日志级别
void log_setlevel(LEVEL_T level)
{
LOG.curlevel = level;
return;
}
log.h
#ifndef __LOG_H__
#define __LOG_H__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <pthread.h>
typedef struct LOG_DATE
{
int year;
int mon;
int day;
}DATE_T;
typedef enum LOG_LEVEL
{
LOG_MASSAGE,
LOG_WORNING,
LOG_ERROR,
}LEVEL_T;
typedef struct log
{
FILE *flog;
LEVEL_T curlevel;
struct tm *curtime;
pthread_mutex_t lock;
}log_t;
extern int log_init(char *pdirname);
extern int log_write(LEVEL_T level,const char *pfile, const int line, const char *pfunc, const char *pstr, ...);
extern int log_deinit(void);
#endif
main.c
#include "log.h"
int main(void)
{
int num = 11451;
log_init("LOG_FILE");
log_write(LOG_MASSAGE, __FILE__,__LINE__,__func__, "===================================================");
log_write(LOG_MASSAGE, __FILE__,__LINE__,__func__, " software log record systerm ");
log_write(LOG_MASSAGE, __FILE__,__LINE__,__func__, "===================================================");
log_write(LOG_MASSAGE, __FILE__,__LINE__,__func__, "hello world %d", num);
log_write(LOG_MASSAGE, __FILE__,__LINE__,__func__, "hello world %d", num);
log_deinit();
return 0;
}
效果: