近段工作中需要记录接受到的数据,由于只是一串字符串,放入数据库实在是没有必要,因此改为写记录日志,别人给了一个日志类,感觉太复杂了,看起来浪费时间,于是自己封装了一个日志类。包括基本的时间戳,日志级别等。
//写文件日志
#ifndef MY_LOG_H
#define MY_LOG_H
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#define FILE_PATH_LEN 128 /*文件路径长度*/
enum value_set_get
{
SETVALUE = 0,
GETVALUE,
};
enum log_level
{
INFO = 0,
ERR,
CRIT,
};
class My_log
{
public:
My_log();
My_log( const char* log_path, const char* log_name );
~My_log();
int open_file(char *path, char* name);
int current_dir(char*, int flag);
int log_path( char*, int flag ); // set or get the log path
int log_name( char*, int flag ); //set or get the log name
int current_dateTime( char*);// get the current date time
int write_log( char* mseesage, int info_level );//write log
int get_initParam( char* file_name, const char *name, char* para);//get the inti param
char* trim(char *str); //delete the space
int is_directory(char*);
int current_dir_default();
private:
char m_log_path[FILE_PATH_LEN];
char m_log_name[FILE_PATH_LEN];
char m_start_dateTime[FILE_PATH_LEN];
char m_init_fileName[FILE_PATH_LEN];
char m_init_filePath[FILE_PATH_LEN];
char m_curren_dir[FILE_PATH_LEN];
int m_logfd;
char m_system_name[FILE_PATH_LEN];
char m_version[FILE_PATH_LEN];
char m_old_day[9];
};
#endif // MY_LOG_H
实现文件:
如果在多线程中,需要考虑同步情况,对写操作进行加锁
#include "my_log.h"
#include <stdio.h>
My_log::My_log()
{
//init
memset(m_log_name, 0, sizeof(m_log_name));
memset(m_log_path, 0, sizeof(m_log_path));
memset(m_start_dateTime, 0, sizeof(m_start_dateTime));
memset(m_init_fileName, 0, sizeof(m_init_fileName));
memset(m_curren_dir, 0, sizeof(m_curren_dir));
memset(m_old_day, 0, sizeof(m_old_day));
//init file name and path
strncpy( m_init_fileName, "log.ini", strlen("log.ini")); //default
if(current_dir_default()) //set the default dir
{
fprintf(stderr, "get thr current dir error\n");
exit(-1);
}
//get init infomation
if(get_initParam(m_init_fileName, "LOGPATH", m_log_path)
|| get_initParam(m_init_fileName, "SYSTEMNAME", m_system_name)
|| get_initParam(m_init_fileName, "VERSION", m_version))
{
fprintf(stderr, " get the info from inifile [%s] error\n", m_init_fileName);
exit(-1);
}
if(is_directory(m_log_path))
{
fprintf(stderr, "the path is not a valid path\n");
exit(-1);
}
current_dateTime(m_start_dateTime);
strncat(m_log_name, m_system_name, strlen(m_system_name));
strncat(m_log_name, m_version, strlen(m_version));
strncat(m_log_name, m_start_dateTime, 10); //2013111220
strncat(m_old_day, m_start_dateTime, 10);
if(open_file(m_log_path, m_log_name))
{
fprintf(stderr, "open file failed\n");
exit(-1);
}
}
My_log::My_log(const char *log_path, const char *log_name)
{
memset(m_log_name, 0, sizeof(m_log_name));
memset(m_log_path, 0, sizeof(m_log_path));
memset(m_start_dateTime, 0, sizeof(m_start_dateTime));
memset(m_init_fileName, 0, sizeof(m_init_fileName));
memset(m_curren_dir, 0, sizeof(m_curren_dir));
m_logfd = 0;
current_dateTime(m_start_dateTime);
// strncat(m_log_name, m_system_name, strlen(m_system_name));
// strncat(m_log_name, m_version, strlen(m_version));
// strncat(m_log_name, m_start_dateTime, strlen(m_start_dateTime));
strncat(m_log_name, log_name, strlen(log_name));
strncpy(m_log_path, log_path, strlen(log_path));
char time[15] = {0};
current_dateTime(time);
strncat(m_log_name, "_", 1);
strncat(m_log_name, time, 10); //append the time after the name
if(open_file(m_log_path, m_log_name))
{
fprintf(stderr, "open file failed\n");
exit(-1);
}
}
int My_log::open_file(char *path, char *name)
{
if(is_directory(path))
{
fprintf(stderr, "the path is not a valid path\n");
return (-1);
}
if(path[strlen(path) -1] != '/')
{
strcat(path, "/");
}
strcat(path, "log");
if(access(path, F_OK)) //if not exit, create it
{
if(mkdir(path, S_IRWXU))
{
fprintf(stderr, "make dir error : %s\n", strerror(errno));
return (-1);
}
}
if(!access(path, W_OK))
{
chmod(path, S_IRWXU);
}
if(path[strlen(path) -1] != '/')
{
strcat(path, "/");
}
char tmp[FILE_PATH_LEN] = {0};
sprintf(tmp, "%s%s.log", path, name);
if(access(tmp, F_OK))
{
if((m_logfd = open(tmp, O_RDWR|O_CREAT, S_IRWXU)) < 0) //if not exit, create it
{
fprintf(stderr, "open the log file [%s] error : %s\n", tmp, strerror(errno));
return (-1);
}
}
else
{
if(access(tmp, W_OK)) //check the log file can be write
{
if(chmod(tmp, S_IRUSR | S_IWUSR)) //change the mode
{
fprintf(stderr, "chmod [%s] failed : %s\n", tmp, strerror(errno));
return -1;
}
}
if((m_logfd = open(tmp, O_WRONLY|O_APPEND)) < 0) //if eixt, append it
{
fprintf(stderr, "open the log file [%s] error : %s\n", tmp, strerror(errno));
return (-1);
}
}
return 0;
}
My_log::~My_log()
{
close(m_logfd);
}
int My_log::current_dir_default()
{
char dir_name[100];
char *pos;
strcpy(dir_name, get_current_dir_name());
pos = strrchr(dir_name, '/');
*(pos+1) = '\0';
strcat(m_curren_dir, dir_name);
strcat(m_curren_dir, "my_log/");
return 0;
}
int My_log::current_dir(char *dir, int flag)
{
switch(flag)
{
case SETVALUE:
strncpy(m_curren_dir, dir, strlen(dir));
break;
case GETVALUE:
strncpy(dir, m_curren_dir, strlen(m_curren_dir));
break;
}
return 0;
}
int My_log::write_log(char *meesage, int info_level)
{
char buf[512] = {0};
char sinfo_level[5] = {0};
char curr_date_time[15] = {0};
switch(info_level)
{
case INFO:
strcpy(sinfo_level, "INFO");
break;
case ERR:
strcpy(sinfo_level, "WARN");
break;
case CRIT:
strcpy(sinfo_level, "CRIT");
break;
default:
strcpy(sinfo_level, "INFO");
}
current_dateTime(curr_date_time);
if(!strncmp(m_old_day, curr_date_time, 10)) //if a new day, create new log file
{
strncpy(m_old_day, curr_date_time, 10);
if(open_file("./", "com"))
{
fprintf(stderr, "create new log file error\n");
return -1;
}
fprintf(stdout, "create new log file done\n");
}
sprintf(buf, "%s%s::%s\n", sinfo_level, curr_date_time, meesage);
printf("write_log:%s", buf);
write(m_logfd, buf, strlen(buf));
return 0;
}
int My_log::is_directory(char *path)
{
struct stat info;
if(stat(path, &info))
{
fprintf(stderr, "check the path [%s] error\n", path);
return -1;
}
if(info.st_mode & S_IFDIR)
{
return 0;
}
else
{
return 1;
}
}
int My_log::current_dateTime(char *date_time)
{
time_t sys_time;
struct tm *plocal_time;
time(&sys_time);
plocal_time = localtime(&sys_time);
sprintf(date_time, "%04d%02d%02d%02d%02d%02d",
plocal_time->tm_year+1900, plocal_time->tm_mon+1, plocal_time->tm_mday,
plocal_time->tm_hour, plocal_time->tm_min, plocal_time->tm_sec);
// switch(flag)
// {
// case SETVALUE:strncpy(m_current_dateTime, date_time, sizeof(date_time));
// break;
// case GETVALUE:strncpy(date_time, m_current_dateTime, sizeof(m_current_dateTime));
// break;
// }
return 0;
}
int My_log::get_initParam(char *file_name, const char *name, char *para)
{
char line[256] = {0};
char *pos;
FILE *fp;
char tmp[100] = {0};
strncpy(tmp, m_curren_dir, strlen(m_curren_dir));
strcat(tmp, file_name);
if((fp = fopen(tmp, "r")) == NULL)
{
fprintf(stderr, "open inti file [%s] error\n", file_name);
perror("");
return -1;
}
if(fgets(line, 255, fp) == NULL)
{
fprintf(stderr, "read the init file error\n");
perror("");
return -1;
}
while( !feof(fp))
{
pos = strchr( line, '=');
if(pos != NULL)
{
*pos = '\0';
trim(line);
if(strcmp( line, name ) == 0)
{
strcpy(para, pos+1);
trim(para);
fclose(fp);
return 0;
}
}
if(fgets( line, 255, fp) == NULL && !feof(fp))
{
fprintf(stderr, "read the init file error\n");
perror("");
return -1;
}
}
fclose(fp);
return -1;
}
char* My_log::trim(char *str)
{
int len;
char *p;
p =str;
while(isspace((int)(*p)))
p++;
strcpy(str, p);
len = strlen(str);
if(len <= 0)
return str;
while(isspace((int)str[len -1]))
len--;
str[len] = '\0';
return str;
}
int My_log::log_name(char *name, int flag)
{
switch (flag)
{
case SETVALUE:
strncpy(m_log_name , name, strlen(name));
break;
case GETVALUE:
strncpy(name, m_log_name, strlen(m_log_name));
break;
default:
strncpy(name, m_log_name, strlen(m_log_name));
break;
}
}
int My_log::log_path(char *path, int flag)
{
switch (flag)
{
case SETVALUE:
strncpy(m_log_path , path, strlen(path));
break;
case GETVALUE:
strncpy(path, m_log_path, strlen(m_log_path));
break;
default:
strncpy(path, m_log_path, strlen(m_log_path));
break;
}
}
demo示例:
#include <iostream>
#include "my_log.h"
using namespace std;
int main1()
{
My_log log("./", "read_com");
log.write_log("starting", INFO);
sleep(1);
log.write_log("hello world", INFO);
return 0;
}