8. 代码设计
8.1 实用类设计
提前完成⼀些零碎的功能接⼝,以便于项⽬中会⽤到。
• 获取系统时间
• 判断⽂件是否存在
• 获取⽂件的所在⽬录路径
• 创建⽬录
/*
通⽤功能类,与业务⽆关的功能实现
1. 获取系统时间
2. 获取⽂件⼤⼩
3. 创建⽬录
4. 获取⽂件所在⽬录
*/
#ifndef __M_UTIL_H__
#define __M_UTIL_H__
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <ctime>
#include <cassert>
#include <sys/stat.h>
namespace bitlog{
namespace util{
class date {
public:
static size_t now() { return (size_t)time(nullptr); }
};
class file {
public:
static bool exists(const std::string &name) {
struct stat st;
return stat(name.c_str(), &st) == 0;
}
static std::string path(const std::string &name) {
if (name.empty()) return ".";
size_t pos = name.find_last_of("/\\");
if (pos == std::string::npos) return ".";
return name.substr(0, pos + 1);
}
static void create_directory(const std::string &path) {
if (path.empty()) return ;
if (exists(path)) return ;
size_t pos, idx = 0;
while(idx < path.size()) {
pos = path.find_first_of("/\\", idx);
if (pos == std::string::npos) {
mkdir(path.c_str(), 0755);
return;
}
if (pos == idx) {idx = pos + 1; continue;}
std::string subdir = path.substr(0, pos);
if (subdir == "." || subdir == "..")
{idx = pos + 1; continue;}
if (exists(subdir))
{idx = pos + 1; continue;}
mkdir(subdir.c_str(), 0755);
idx = pos + 1;
}
}
};
}
}
#endif
8.2 日志等级类设计
日志等级总共分为7个等级,分别为:
• OFF 关闭所有⽇志输出
• DRBUG 进⾏debug时候打印⽇志的等级
• INFO 打印⼀些⽤⼾提⽰信息
• WARN 打印警告信息
• ERROR 打印错误信息
• FATAL 打印致命信息- 导致程序崩溃的信息
#ifndef __M_LEVEL_H__
#define __M_LEVEL_H__
namespace bitlog{
class LogLevel{
public:
enum class value {
DEBUG,
INFO,
WARN,
ERROR,
FATAL,
OFF
};
static const char *toString(LogLevel::value l) {
switch(l) {
#define TOSTRING(name) #name
case LogLevel::value::DEBUG: return TOSTRING(DEBUG);
case LogLevel::value::INFO: return TOSTRING(INFO);
case LogLevel::value::WARN: return TOSTRING(WARN);
case LogLevel::value::ERROR: return TOSTRING(ERROR);
case LogLevel::value::FATAL: return TOSTRING(FATAL);
case LogLevel::value::OFF: return TOSTRING(OFF);
#undef TOSTRING
default: return "UNKNOW";
}
return "UNKNOW";
}
};
}
#endif
8.3 日志消息类设计
日志消息类主要是封装⼀条完整的⽇志消息所需的内容,其中包括⽇志等级、对应的logger name、打印日志源⽂件的位置信息(包括⽂件名和⾏号)、线程ID、时间戳信息、具体的⽇志信息等内容。
#ifndef __M_MSG_H__
#define __M_MSG_H__
#include "util.hpp"
#include "level.hpp"
#include <thread>
namespace bitlog{
struct LogMsg {
using ptr = std::shared_ptr<LogMsg>;
size_t _line;//⾏号
size_t _ctime;//时间
std::thread::id _tid;//线程ID
std::string _name;//⽇志器名称
std::string _file;//⽂件名
std::string _payload;//⽇志消息
LogLevel::value _level;//⽇志等级
LogMsg() {}
LogMsg( std::string name,
std::string file,
size_t line,
std::string payload,
LogLevel::value level):
_name(name),
_file(file),
_payload(payload),
_level(level),
_line(line),
_ctime(util:: date::now()),
_tid(std::this_thread::get_id()) {}
};
}
#endif