-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlogger.cpp
More file actions
78 lines (68 loc) · 1.79 KB
/
logger.cpp
File metadata and controls
78 lines (68 loc) · 1.79 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
// logger.cpp
// prints messages with timestamp to screen and to the log file
#include "logger.h"
#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
RunLogger::RunLogger(std::string logFileName)
: fileIsOpen(false)
{
if (!logFileName.empty())
{
openLogFile.open(logFileName, std::ios::out | std::ios::app);
if (openLogFile.is_open())
fileIsOpen = true;
}
}
RunLogger::~RunLogger()
{
if (fileIsOpen)
openLogFile.close();
}
std::string RunLogger::getCurrentTimestamp()
{
auto nowPoint = std::chrono::system_clock::now();
std::time_t nowTime = std::chrono::system_clock::to_time_t(nowPoint);
std::ostringstream buf;
std::tm tmBuf{};
localtime_s(&tmBuf, &nowTime);
buf << std::put_time(&tmBuf, "%H:%M:%S");
return buf.str();
}
void RunLogger::write(std::string msg)
{
std::string fullLine = "[" + getCurrentTimestamp() + "] " + msg;
std::cout << fullLine << std::endl;
if (fileIsOpen)
openLogFile << fullLine << "\n";
}
void RunLogger::writeLabeled(std::string label, long long numberVal)
{
write(label + ": " + std::to_string(numberVal));
}
void RunLogger::writeLabeled(std::string label, double numberVal)
{
std::ostringstream buf;
buf << std::fixed << std::setprecision(4) << numberVal;
write(label + ": " + buf.str());
}
void RunLogger::writeLabeled(std::string label, std::string textVal)
{
write(label + ": " + textVal);
}
void RunLogger::writeSeparator()
{
std::string line = "------------------------------------------";
std::cout << line << std::endl;
if (fileIsOpen)
openLogFile << line << "\n";
}
void RunLogger::writeBlankLine()
{
std::cout << " " << std::endl;
if (fileIsOpen)
openLogFile << "\n";
}
// logger.cpp