blob: 7a66c16a68cd9026d1d61f500ba7626b682711d7 [file] [log] [blame]
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -05001#include "logger.hpp"
2
Souvik Roy8042bbf2025-10-06 09:16:50 +00003#include <regex>
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -05004#include <sstream>
5
6namespace vpd
7{
Sunny Srivastava5779d972025-08-08 01:45:23 -05008std::shared_ptr<Logger> Logger::m_loggerInstance;
9
10void Logger::logMessage(std::string_view i_message,
11 const PlaceHolder& i_placeHolder,
12 const types::PelInfoTuple* i_pelTuple,
13 const std::source_location& i_location)
14{
15 std::ostringstream l_log;
16 l_log << "FileName: " << i_location.file_name() << ","
17 << " Line: " << i_location.line() << " " << i_message;
18
Souvik Roya5e18b82025-09-25 05:59:56 +000019 if ((i_placeHolder == PlaceHolder::COLLECTION) && m_collectionLogger)
Sunny Srivastava5779d972025-08-08 01:45:23 -050020 {
Alpana Kumari37ce6e32025-10-23 06:37:59 -050021#ifdef ENABLE_FILE_LOGGING
Sunny Srivastava5779d972025-08-08 01:45:23 -050022 // Log it to a specific place.
Souvik Roya8c3c092025-09-11 10:49:29 +000023 m_collectionLogger->logMessage(l_log.str());
Alpana Kumari37ce6e32025-10-23 06:37:59 -050024#else
25 std::cout << l_log.str() << std::endl;
26#endif
Sunny Srivastava5779d972025-08-08 01:45:23 -050027 }
28 else if (i_placeHolder == PlaceHolder::PEL)
29 {
30 if (i_pelTuple)
31 {
32 // LOG PEL
33 // This should call create PEL API from the event logger.
34 return;
35 }
36 std::cout << "Pel info tuple required to log PEL for message <" +
37 l_log.str() + ">"
38 << std::endl;
39 }
Souvik Roya5e18b82025-09-25 05:59:56 +000040 else if ((i_placeHolder == PlaceHolder::VPD_WRITE) && m_vpdWriteLogger)
41 {
Souvik Roya8c3c092025-09-11 10:49:29 +000042 m_vpdWriteLogger->logMessage(l_log.str());
Souvik Roya5e18b82025-09-25 05:59:56 +000043 }
Sunny Srivastava5779d972025-08-08 01:45:23 -050044 else
45 {
46 // Default case, let it go to journal.
47 std::cout << l_log.str() << std::endl;
48 }
49}
50
Souvik Roya5e18b82025-09-25 05:59:56 +000051void Logger::initiateVpdCollectionLogging() noexcept
52{
53 try
54 {
Souvik Roy8042bbf2025-10-06 09:16:50 +000055 // collection log file directory
56 const std::filesystem::path l_collectionLogDirectory{"/var/lib/vpd"};
57
58 std::error_code l_ec;
59 if (!std::filesystem::exists(l_collectionLogDirectory, l_ec))
60 {
61 if (l_ec)
62 {
63 throw std::runtime_error(
64 "File system call to exist failed with error = " +
65 l_ec.message());
66 }
67 throw std::runtime_error(
68 "Directory " + l_collectionLogDirectory.string() +
69 " does not exist");
70 }
71
72 // base name of collection log file
73 std::filesystem::path l_collectionLogFilePath{l_collectionLogDirectory};
74 l_collectionLogFilePath /= "collection";
75
76 unsigned l_collectionLogFileCount{0};
77
78 std::filesystem::file_time_type l_oldestFileTime;
79 std::filesystem::path l_oldestFilePath{l_collectionLogFilePath};
80
81 // iterate through all entries in the log directory
82 for (const auto& l_dirEntry :
83 std::filesystem::directory_iterator(l_collectionLogDirectory))
84 {
85 // check /var/lib/vpd for number "collection.*" log file
86 const std::regex l_collectionLogFileRegex{"collection.*\\.log"};
87
88 if (std::filesystem::is_regular_file(l_dirEntry.path()) &&
89 std::regex_match(l_dirEntry.path().filename().string(),
90 l_collectionLogFileRegex))
91 {
92 // check the write time of this file
93 const auto l_fileWriteTime =
94 std::filesystem::last_write_time(l_dirEntry.path());
95
96 // update oldest file path if required
97 if (l_fileWriteTime < l_oldestFileTime)
98 {
99 l_oldestFileTime = l_fileWriteTime;
100 l_oldestFilePath = l_dirEntry.path();
101 }
102
103 l_collectionLogFileCount++;
104 }
105 }
106
107 // maximum number of collection log files to maintain
108 constexpr auto l_maxCollectionLogFiles{3};
109
110 if (l_collectionLogFileCount >= l_maxCollectionLogFiles)
111 {
112 // delete oldest collection log file
113 l_collectionLogFilePath = l_oldestFilePath;
114
115 logMessage("Deleting collection log file " +
116 l_collectionLogFilePath.string());
117
118 std::error_code l_ec;
119 if (!std::filesystem::remove(l_collectionLogFilePath, l_ec))
120 {
121 logMessage("Failed to delete existing collection log file " +
122 l_collectionLogFilePath.string() +
123 " Error: " + l_ec.message());
124 }
125 }
126 else
127 {
128 l_collectionLogFilePath +=
129 "_" + std::to_string(l_collectionLogFileCount) + ".log";
130 }
131
132 // create collection logger object with collection_(n+1).log
Souvik Roy0fb5c3b2025-09-15 08:18:25 +0000133 m_collectionLogger.reset(
Souvik Roy8042bbf2025-10-06 09:16:50 +0000134 new AsyncFileLogger(l_collectionLogFilePath, 4096));
Souvik Roya5e18b82025-09-25 05:59:56 +0000135 }
136 catch (const std::exception& l_ex)
137 {
138 logMessage("Failed to initialize collection logger. Error: " +
139 std::string(l_ex.what()));
140 }
141}
142
Souvik Roy6bd74ad2025-09-12 06:24:06 +0000143void SyncFileLogger::logMessage(const std::string_view& i_message)
144{
145 try
146 {
Souvik Royd834b122025-10-28 06:37:51 +0000147 if (m_currentNumEntries >= m_maxEntries)
Souvik Roy6bd74ad2025-09-12 06:24:06 +0000148 {
149 rotateFile();
150 }
Souvik Royd834b122025-10-28 06:37:51 +0000151
152 std::string l_timeStampedMsg{
153 timestamp() + " : " + std::string(i_message)};
154
155 // check size of message and pad/trim as required
156 if (l_timeStampedMsg.length() > m_logEntrySize)
157 {
158 l_timeStampedMsg.resize(m_logEntrySize);
159 }
160 else if (l_timeStampedMsg.length() < m_logEntrySize)
161 {
162 constexpr char l_padChar{' '};
163 l_timeStampedMsg.append(m_logEntrySize - l_timeStampedMsg.length(),
164 l_padChar);
165 }
166
167 // write the message to file
168 m_fileStream << l_timeStampedMsg << std::endl;
169
170 // increment number of entries only if write to file is successful
171 ++m_currentNumEntries;
Souvik Roy6bd74ad2025-09-12 06:24:06 +0000172 }
173 catch (const std::exception& l_ex)
174 {
175 // log message to journal if we fail to log to file
176 auto l_logger = Logger::getLoggerInstance();
177 l_logger->logMessage(i_message);
178 }
179}
180
Souvik Royf8587362025-09-25 09:56:20 +0000181void AsyncFileLogger::logMessage(const std::string_view& i_message)
Souvik Roy0fb5c3b2025-09-15 08:18:25 +0000182{
183 try
184 {
Souvik Royf8587362025-09-25 09:56:20 +0000185 // acquire lock on queue
186 std::unique_lock<std::mutex> l_lock(m_mutex);
187
188 // push message to queue
189 m_messageQueue.emplace(timestamp() + " : " + std::string(i_message));
190
191 // notify log worker thread
192 m_cv.notify_one();
Souvik Roy0fb5c3b2025-09-15 08:18:25 +0000193 }
194 catch (const std::exception& l_ex)
195 {
Souvik Royf8587362025-09-25 09:56:20 +0000196 // log message to journal if we fail to push message to queue
197 Logger::getLoggerInstance()->logMessage(i_message);
Souvik Roy0fb5c3b2025-09-15 08:18:25 +0000198 }
199}
200
201void AsyncFileLogger::fileWorker() noexcept
202{
Souvik Royf8587362025-09-25 09:56:20 +0000203 // create lock object on mutex
204 std::unique_lock<std::mutex> l_lock(m_mutex);
205
206 // infinite loop
207 while (true)
208 {
209 // check for exit conditions
210 if (!m_fileStream.is_open() || m_stopLogging)
211 {
212 break;
213 }
214
215 // wait for notification from log producer
216 m_cv.wait(l_lock,
217 [this] { return m_stopLogging || !m_messageQueue.empty(); });
218
219 // flush the queue
220 while (!m_messageQueue.empty())
221 {
222 // read the first message in queue
223 const auto l_logMessage = m_messageQueue.front();
224 try
225 {
226 // pop the message from queue
227 m_messageQueue.pop();
228
229 // unlock mutex on queue
230 l_lock.unlock();
231
Souvik Royf8587362025-09-25 09:56:20 +0000232 // flush the message to file
233 m_fileStream << l_logMessage << std::endl;
234
235 // lock mutex on queue
236 l_lock.lock();
237 }
238 catch (const std::exception& l_ex)
239 {
240 // log message to journal if we fail to push message to queue
241 Logger::getLoggerInstance()->logMessage(l_logMessage);
242
243 // check if we need to reacquire lock before continuing to flush
244 // queue
245 if (!l_lock.owns_lock())
246 {
247 l_lock.lock();
248 }
249 }
250 } // queue flush loop
251 } // thread loop
Souvik Roy0fb5c3b2025-09-15 08:18:25 +0000252}
253
Souvik Roybac8ba62025-10-27 09:07:06 +0000254ILogFileHandler::ILogFileHandler(const std::filesystem::path& i_filePath,
255 const size_t i_maxEntries) :
256 m_filePath{i_filePath}, m_maxEntries{i_maxEntries}
257{
258 // check if log file already exists
259 std::error_code l_ec;
260 const bool l_logFileExists = std::filesystem::exists(m_filePath, l_ec);
261 if (l_ec)
262 {
263 Logger::getLoggerInstance()->logMessage(
264 "Failed to check if log file already exists. Error: " +
265 l_ec.message());
266 }
267
268 // open the file in append mode
Souvik Royd834b122025-10-28 06:37:51 +0000269 m_fileStream.open(m_filePath, std::ios::out | std::ios::ate);
Souvik Roybac8ba62025-10-27 09:07:06 +0000270 // enable exception mask to throw on badbit and failbit
271 m_fileStream.exceptions(std::ios_base::badbit | std::ios_base::failbit);
272
273 if (l_logFileExists)
274 {
275 // log file already exists, check and update the number of entries
276 std::ifstream l_readFileStream{m_filePath};
277 for (std::string l_line; std::getline(l_readFileStream, l_line);
278 ++m_currentNumEntries)
279 {}
280
281 l_readFileStream.close();
282 }
283}
284
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500285namespace logging
286{
287void logMessage(std::string_view message, const std::source_location& location)
288{
289 std::ostringstream log;
290 log << "FileName: " << location.file_name() << ","
291 << " Line: " << location.line() << " " << message;
292
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500293 std::cout << log.str() << std::endl;
294}
295} // namespace logging
296} // namespace vpd