-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimestampLogger.h
More file actions
82 lines (72 loc) · 2.56 KB
/
TimestampLogger.h
File metadata and controls
82 lines (72 loc) · 2.56 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
#pragma once
#include "StreamLineWriter.h"
#include <Windows.h>
#include <string>
class TimestampLogger
{
public:
TimestampLogger(const std::wstring& filepath)
: TimestampLogger(filepath, FALSE) { }
TimestampLogger(const std::wstring& filepath, BOOL autoflush)
: streamlinewriter_(StreamLineWriter(filepath, TRUE))
{
pwritecriticalsection_ = new CRITICAL_SECTION();
if (!InitializeCriticalSectionAndSpinCount(pwritecriticalsection_, 0x00000400))
{
// TODO: handle error
}
set_autoflush(autoflush);
}
~TimestampLogger()
{
if (pwritecriticalsection_ != nullptr)
{
DeleteCriticalSection(pwritecriticalsection_);
delete pwritecriticalsection_;
}
Close();
}
TimestampLogger(const TimestampLogger&) = delete;
TimestampLogger& operator=(const TimestampLogger&) = delete;
void WriteLine(const std::wstring& line);
void Close()
{
streamlinewriter_.Close();
}
BOOL autoflush() const { return streamlinewriter_.autoflush(); };
void set_autoflush(BOOL autoflush) { streamlinewriter_.set_autoflush(autoflush); };
static std::wstring GetTimestampString();
static std::wstring GetTimestampString(BOOL asvalidfilename);
private:
StreamLineWriter streamlinewriter_;
PCRITICAL_SECTION pwritecriticalsection_{ nullptr };
};
inline void TimestampLogger::WriteLine(const std::wstring& line)
{
EnterCriticalSection(pwritecriticalsection_);
SYSTEMTIME filetime;
GetLocalTime(&filetime);
std::wstringstream wss;
wss << L"[" << GetTimestampString() << L"] ";
streamlinewriter_.WriteLine(wss.str() + line);
LeaveCriticalSection(pwritecriticalsection_);
}
inline std::wstring TimestampLogger::GetTimestampString()
{
return GetTimestampString(FALSE);
}
inline std::wstring TimestampLogger::GetTimestampString(BOOL asvalidfilename)
{
SYSTEMTIME filetime;
GetLocalTime(&filetime);
std::wstringstream wss;
const auto timeseparator = asvalidfilename ? L"." : L":";
wss << filetime.wYear << L"-";
wss << std::setw(2) << std::setfill(L'0') << filetime.wMonth << L"-";
wss << std::setw(2) << std::setfill(L'0') << filetime.wDay << L"T";
wss << std::setw(2) << std::setfill(L'0') << filetime.wHour << timeseparator;
wss << std::setw(2) << std::setfill(L'0') << filetime.wMinute << timeseparator;
wss << std::setw(2) << std::setfill(L'0') << filetime.wSecond << L".";
wss << std::setw(3) << std::setfill(L'0') << filetime.wMilliseconds;
return wss.str();
}