-
Notifications
You must be signed in to change notification settings - Fork 0
/
Log.h
81 lines (66 loc) · 1.86 KB
/
Log.h
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
/*
* Copyright (c) 2024 Nils Zweiling
*
* This file is part of fusecache which is released under the MIT license.
* See file LICENSE or go to https://github.com/zwodev/fusecache/tree/master/LICENSE
* for full license details.
*/
#pragma once
#include <ctime>
#include <fstream>
#include <iostream>
#include <sstream>
class Log {
public:
Log () {}
Log(const std::string& filename, bool logToCommandline = false)
{
m_logToCommandline = false;
m_filename = filename;
m_logFile.open(filename, std::ios::app | std::ios::out);
if (!m_logFile.is_open()) {
std::cerr << "Error opening log file." << std::endl;
}
}
~Log()
{
m_logFile.close();
}
void debug(const std::string& message) {
writeLog("DEBUG", message);
}
void info(const std::string& message) {
writeLog("INFO", message);
}
void warning(const std::string& message) {
writeLog("WARNING", message);
}
void error(const std::string& message) {
writeLog("ERROR", message);
}
private:
void writeLog(const std::string& level, const std::string& message)
{
time_t now = time(0);
tm* timeinfo = localtime(&now);
char timestamp[20];
strftime(timestamp, sizeof(timestamp),
"%Y-%m-%d %H:%M:%S", timeinfo);
std::ostringstream logEntry;
logEntry << "[" << timestamp << "] "
<< level << ": " << message
<< std::endl;
if (m_logToCommandline) {
std::cout << logEntry.str();
}
if (m_logFile.is_open()) {
m_logFile << logEntry.str();
m_logFile
.flush();
}
}
private:
std::ofstream m_logFile;
std::string m_filename;
bool m_logToCommandline = false;
};