Repository navigation
Expand file tree
/
Copy pathLog.cpp
More file actions
78 lines (65 loc) · 2.25 KB
/
Copy pathLog.cpp
File metadata and controls
78 lines (65 loc) · 2.25 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
#include "Log.h"
#include <windows.h>
#include <mutex>
#include "Common.h"
#include "Settings.h"
namespace {
// Big enough to cover a long unattended run, small enough to read and to mail.
constexpr long long kMaxLogBytes = 256 * 1024;
std::mutex g_logMutex;
std::wstring Timestamp()
{
SYSTEMTIME now = {};
GetLocalTime(&now);
wchar_t stamp[32];
swprintf_s(stamp, L"%04u-%02u-%02u %02u:%02u:%02u ",
now.wYear, now.wMonth, now.wDay, now.wHour, now.wMinute, now.wSecond);
return stamp;
}
// Keeps one previous file so a problem is not erased by the noise that follows
// it. Rolling beats truncating: the interesting line is usually the first.
void RollIfLarge(const std::wstring& path)
{
WIN32_FILE_ATTRIBUTE_DATA data = {};
if (!GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &data))
return;
long long size = (static_cast<long long>(data.nFileSizeHigh) << 32) | data.nFileSizeLow;
if (size < kMaxLogBytes)
return;
std::wstring previous = path + L".1";
DeleteFileW(previous.c_str());
MoveFileW(path.c_str(), previous.c_str());
}
} // namespace
std::wstring LogFilePath()
{
std::wstring settings = SettingsFilePath();
if (settings.empty())
return {};
size_t slash = settings.find_last_of(L'\\');
if (slash == std::wstring::npos)
return {};
return settings.substr(0, slash) + L"\\wallpaperchanger.log";
}
void LogLine(const std::wstring& text)
{
try {
std::wstring path = LogFilePath();
if (path.empty())
return;
std::lock_guard<std::mutex> lock(g_logMutex);
RollIfLarge(path);
// UTF-8 so the file opens cleanly anywhere, appended with a single
// write so lines from different threads cannot interleave.
std::string line = Narrow(Timestamp() + text) + "\r\n";
HANDLE file = CreateFileW(path.c_str(), FILE_APPEND_DATA, FILE_SHARE_READ,
nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE)
return;
DWORD written = 0;
WriteFile(file, line.data(), static_cast<DWORD>(line.size()), &written, nullptr);
CloseHandle(file);
} catch (...) {
// A failure to log is never worth propagating.
}
}