-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathFileLogger.cpp
More file actions
234 lines (196 loc) · 7.84 KB
/
FileLogger.cpp
File metadata and controls
234 lines (196 loc) · 7.84 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include "Public/AppInstallerFileLogger.h"
#include "Public/AppInstallerRuntime.h"
#include "Public/AppInstallerStrings.h"
#include "Public/AppInstallerDateTime.h"
#include "Public/winget/UserSettings.h"
#include <winget/Filesystem.h>
#include <corecrt_io.h>
namespace AppInstaller::Logging
{
using namespace std::string_view_literals;
using namespace std::chrono_literals;
namespace
{
static constexpr std::string_view s_fileLoggerDefaultFilePrefix = "WinGet"sv;
static constexpr std::string_view s_fileLoggerDefaultFileExt = ".log"sv;
// Send to a string first to create a single block to write to a file.
std::string ToLogLine(Channel channel, std::string_view message)
{
std::stringstream strstr;
strstr << std::chrono::system_clock::now() << " [" << std::setw(GetMaxChannelNameLength()) << std::left << std::setfill(' ') << GetChannelName(channel) << "] " << message;
return std::move(strstr).str();
}
// Determines the difference between the given position and the maximum as an offset.
std::ofstream::off_type CalculateDiff(const std::ofstream::pos_type& position, std::ofstream::off_type maximum)
{
auto offsetPosition = static_cast<std::ofstream::off_type>(position);
return maximum > offsetPosition ? maximum - offsetPosition : 0;
}
}
FileLogger::FileLogger() : FileLogger(s_fileLoggerDefaultFilePrefix) {}
FileLogger::FileLogger(const std::filesystem::path& filePath)
{
m_name = GetNameForPath(filePath);
m_filePath = filePath;
InitializeDefaultMaximumFileSize();
OpenFileLoggerStream();
}
FileLogger::FileLogger(const std::string_view fileNamePrefix)
{
m_name = "file";
m_filePath = Runtime::GetPathTo(Runtime::PathName::DefaultLogLocation);
m_filePath /= fileNamePrefix.data() + ('-' + Utility::GetCurrentTimeForFilename() + s_fileLoggerDefaultFileExt.data());
InitializeDefaultMaximumFileSize();
OpenFileLoggerStream();
}
FileLogger::~FileLogger()
{
m_stream.flush();
// When std::ofstream is constructed from an existing File handle, it does not call fclose on destruction
// Only calling close() explicitly will close the file handle.
m_stream.close();
}
FileLogger& FileLogger::SetMaximumSize(std::ofstream::off_type maximumSize)
{
THROW_HR_IF(E_INVALIDARG, maximumSize < 0);
m_maximumSize = maximumSize;
return *this;
}
std::string FileLogger::GetNameForPath(const std::filesystem::path& filePath)
{
using namespace std::string_literals;
return "file :: "s + filePath.u8string();
}
std::string_view FileLogger::DefaultPrefix()
{
return s_fileLoggerDefaultFilePrefix;
}
std::string_view FileLogger::DefaultExt()
{
return s_fileLoggerDefaultFileExt;
}
std::string FileLogger::GetName() const
{
return m_name;
}
void FileLogger::Write(Channel channel, Level level, std::string_view message) noexcept try
{
std::string log = ToLogLine(channel, message);
WriteDirect(channel, level, log);
}
catch (...) {}
void FileLogger::WriteDirect(Channel, Level, std::string_view message) noexcept try
{
HandleMaximumFileSize(message);
m_stream << message << std::endl;
}
catch (...) {}
void FileLogger::SetTag(Tag tag) noexcept try
{
if (tag == Tag::HeadersComplete)
{
auto currentPosition = m_stream.tellp();
if (currentPosition != std::ofstream::pos_type{ -1 })
{
m_headersEnd = currentPosition;
}
}
}
catch (...) {}
void FileLogger::Add()
{
Log().AddLogger(std::make_unique<FileLogger>());
}
void FileLogger::Add(const std::filesystem::path& filePath)
{
Log().AddLogger(std::make_unique<FileLogger>(filePath));
}
void FileLogger::Add(std::string_view fileNamePrefix)
{
Log().AddLogger(std::make_unique<FileLogger>(fileNamePrefix));
}
void FileLogger::BeginCleanup()
{
BeginCleanup(Runtime::GetPathTo(Runtime::PathName::DefaultLogLocation));
}
void FileLogger::BeginCleanup(const std::filesystem::path& filePath)
{
std::thread([filePath]()
{
try
{
const auto& settings = Settings::User();
Filesystem::FileLimits fileLimits;
fileLimits.Age = settings.Get<Settings::Setting::LoggingFileAgeLimitInDays>();
fileLimits.TotalSizeInMB = settings.Get<Settings::Setting::LoggingFileTotalSizeLimitInMB>();
fileLimits.Count = settings.Get<Settings::Setting::LoggingFileCountLimit>();
auto filesInPath = Filesystem::GetFileInfoFor(filePath);
Filesystem::FilterToFilesExceedingLimits(filesInPath, fileLimits);
for (const auto& file : filesInPath)
{
std::filesystem::remove(file.Path);
}
}
// Just throw out everything
catch (...) {}
}).detach();
}
void FileLogger::OpenFileLoggerStream()
{
// Prevent other writers to our log file, but allow readers
FILE* filePtr = _wfsopen(m_filePath.wstring().c_str(), L"w", _SH_DENYWR);
if (filePtr)
{
auto closeFile = wil::scope_exit([&]() { fclose(filePtr); });
// Prevent inheritance to ensure log file handle is not opened by other processes
THROW_IF_WIN32_BOOL_FALSE(SetHandleInformation(reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(filePtr))), HANDLE_FLAG_INHERIT, 0));
m_stream = std::ofstream{ filePtr };
closeFile.release();
}
else
{
AICLI_LOG(Core, Error, << "Failed to open log file " << m_filePath.u8string());
throw std::system_error(errno, std::generic_category());
}
}
void FileLogger::InitializeDefaultMaximumFileSize()
{
m_maximumSize = static_cast<std::ofstream::off_type>(Settings::User().Get<Settings::Setting::LoggingFileIndividualSizeLimitInMB>()) << 20;
}
void FileLogger::HandleMaximumFileSize(std::string_view& currentLog)
{
if (m_maximumSize == 0)
{
return;
}
auto maximumLogSize = static_cast<size_t>(CalculateDiff(m_headersEnd, m_maximumSize));
// In the event that a single log is larger than the maximum
if (currentLog.size() > maximumLogSize)
{
currentLog = currentLog.substr(0, maximumLogSize);
WrapLogFile();
return;
}
auto currentPosition = m_stream.tellp();
if (currentPosition == std::ofstream::pos_type{ -1 })
{
// The expectation is that if the stream is in an error state the write won't actually happen.
return;
}
auto availableSpace = static_cast<size_t>(CalculateDiff(currentPosition, m_maximumSize));
if (currentLog.size() > availableSpace)
{
WrapLogFile();
return;
}
}
void FileLogger::WrapLogFile()
{
m_stream.seekp(m_headersEnd);
// Yes, we may go over the size limit slightly due to this and the unaccounted for newlines
m_stream << ToLogLine(Channel::Core, "--- log file has wrapped ---") << std::endl;
}
}