【代码整理】同步&异步⽇志系统的代码复盘
在项目的介绍博客🔗中,我们着重于代码功能的实现,
而对项目代码整体的结构和风格欠缺重视,使其可读性有所欠缺,代码规范性也有所不足。所以在这篇博客中,我们将按上篇博客编写代码的顺序,
再一次回顾写好的代码,并着重于:
- 调整代码结构
- 增加必要注释,删除冗余注释
- 添加必要的小括号,突出优先级
- 将代码的简便写法改写回易读的写法
实用类
- 增加功能简介
- 增加注释
- 增加空行c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//提供各种实用类,内部封装了实用接口
namespace suplog{
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配合stat函数作为输出型参数
struct stat st;
//stat获取文件的状态,若成功获取,就会返回0,可用于判断文件是否存在,stat函数是系统调用接口
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("/\\");//找到最后一个"/"或"\\"
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,index = 0;//pos标记所要创建的目录,index用于找"/"
while(index<path.size())
{
//找到index及以后的"/"
pos = path.find_first_of("/\\",index);
if(pos == std::string::npos)
{
//创建最后一层目录
mkdir(path.c_str(),0755);
//函数出口
return;
}
//二者重叠时,跳到下一次循环
if(pos ==index) {index = pos+1;continue;}
//准备创建目录,准备路径
std::string subdir = path.substr(0,pos);
//文件夹已存在,不用创建,跳到下一段即可
if(subdir == "." || subdir == "..")
{index = pos + 1;continue;}
if(exists(subdir))//理由同上
{index = pos + 1;continue;}
//创建目录文件,权限为0755
mkdir(subdir.c_str(),0755);
index = pos + 1;
}
}
};
}
}
日志等级类
- 提供功能描述
- 增加注释
c++
1 |
|
日志消息类
- 增加功能描述
- 增加注释
注释勘误
- 对
shared_ptr
的注释有误,不是全局唯一,是全局引用计数的智能指针
c++
1 |
|
日志输出格式化类
- 修改每个
FormatItem
- 增加注释对功能的描述
- 增加
override
标记为虚函数重写 - 增加
return
强调成员函数的函数身份
- 增加对
Foramtter
类的更详细注释 - 调整私有成员到类的最后,把共有成员提前
c++
1 |
|
日志落地类
- 增加注释
c++
1 |
|
日志类
- 为更多接口添加功能描述
- 使用注释为代码分块
- 调整接口函数的括号位置,使格式统一
- 为
void
函数添加return
,标记函数结尾
补丁
内部的Build
类未提供清空_sinks
的接口,遂添加clearSink
接口
c++
1 | protected: |
修改后的代码
c++
1 |
|
同步日志器类
- 增加注释和调整函数结构
c++
1 | //同步日志器 |
本地日志器建造者类
- 增加注释
c++
1 | //本地日志器建造者 |
双缓冲区异步任务处理器
Buffer类
- 增加注释
- 调整函数结构
c++
1 |
|
AsyncLooper 类
- 增加注释
- 修改变量名
al
为alooper
,防止与之前出现过的变量发生含义混淆,影响代码理解
c++
1 |
|
异步日志器
- 增加注释
- 增加
return
c++
1 | //异步日志器 |
单例日志器管理类
- 基本没有改动
全局日志建造者
- 基本没有改动
suplog.hpp
- 无变化
小结
这次整理代码,一方面是增加了其可读性,使其看起来更优雅,更整齐,另一方面也是再一次加深对项目的理解,顺便还能勘误 👆🤓
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 supdriver的博客!
评论