-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.cpp
110 lines (98 loc) · 2.28 KB
/
log.cpp
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <QDate>
#include "log.h"
const char *SETTINGS_CATEGORY_LOGGING="Logging";
Log::Log(QObject *parent) : QObject(parent),
settingLogDirectory(SETTINGS_CATEGORY_LOGGING,"Directory",Filesystem::DataPath().absoluteFilePath("logs"))
{
file.setFileName(QDir(settingLogDirectory).absoluteFilePath("current"));
}
Log::~Log()
{
Close();
}
bool Log::CreateDirectory()
{
QDir directory(settingLogDirectory);
const char *operation="creating log directory";
Write({directory.absolutePath(),operation});
if (!directory.exists() && !directory.mkpath(directory.absolutePath()))
{
Write({QString("Failed: %1").arg(directory.absolutePath()),operation});
return false;
}
return true;
}
bool Log::Open()
{
const char *operation="create log file";
Write({file.fileName(),operation});
if (!CreateDirectory()) return false;
if (!file.open(QIODevice::ReadWrite|QIODevice::Truncate))
{
Write({"Failed",operation});
return false;
}
return true;
}
void Log::Close()
{
Write({file.fileName(),"close log file"});
file.close();
}
void Log::Write(const Entry &entry)
{
emit Print(entry);
hold.push(entry);
if (!file.isOpen()) return;
while (!hold.empty())
{
if (file.write(hold.front()) < 0 || !file.flush())
{
hold.push({"Failed","write to log file"});
return;
}
hold.pop();
}
}
void Log::Receive(const QString &message,const QString &operation,const QString &subsystem)
{
Write({message,operation,subsystem});
}
void Log::Archive()
{
const char *operation="archive log";
QFile datedFile(QDir(settingLogDirectory).absoluteFilePath(QDate::currentDate().toString("yyyyMMdd.log")));
if (datedFile.exists())
{
if (!file.reset())
{
Write({"Failed to seek to beginning of file",operation});
return;
}
if (!datedFile.open(QIODevice::WriteOnly|QIODevice::Append))
{
Write({"Could not open log file for today's date",operation});
return;
}
while (!file.atEnd())
{
if (datedFile.write(file.read(4096)) < 0)
{
Write({"Could not append to archived log file",operation});
return;
}
}
}
else
{
if (!file.rename(QFileInfo(datedFile).absoluteFilePath())) // rename will close the file for you, per Qt docs
{
Write({"Could not save log as archive file",operation});
return;
}
}
}
ApplicationSetting& Log::Directory()
{
return settingLogDirectory;
}