blob: 742cf27848a42db8448bcda4a97d22ea3ea3dc00 [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,
Souvik Roy2f390432025-11-14 08:07:04 +000013 const std::source_location& i_location) noexcept
Sunny Srivastava5779d972025-08-08 01:45:23 -050014{
15 std::ostringstream l_log;
16 l_log << "FileName: " << i_location.file_name() << ","
17 << " Line: " << i_location.line() << " " << i_message;
18
Souvik Roy2f390432025-11-14 08:07:04 +000019 try
Sunny Srivastava5779d972025-08-08 01:45:23 -050020 {
Souvik Roy2f390432025-11-14 08:07:04 +000021 if (i_placeHolder == PlaceHolder::COLLECTION)
Alpana Kumari138489f2025-11-10 08:59:20 -060022 {
Souvik Roy2f390432025-11-14 08:07:04 +000023#ifdef ENABLE_FILE_LOGGING
24 if (m_collectionLogger.get() == nullptr)
Alpana Kumari138489f2025-11-10 08:59:20 -060025 {
Souvik Roy2f390432025-11-14 08:07:04 +000026 initiateVpdCollectionLogging();
27
28 if (m_collectionLogger.get() != nullptr)
29 {
30 // Log it to a specific place.
31 m_collectionLogger->logMessage(l_log.str());
32 }
33 else
34 {
35 std::cout << l_log.str() << std::endl;
36 }
Alpana Kumari138489f2025-11-10 08:59:20 -060037 }
38 else
39 {
Souvik Roy2f390432025-11-14 08:07:04 +000040 m_collectionLogger->logMessage(l_log.str());
Alpana Kumari138489f2025-11-10 08:59:20 -060041 }
Souvik Roy2f390432025-11-14 08:07:04 +000042#else
43 std::cout << l_log.str() << std::endl;
44#endif
45 }
46 else if (i_placeHolder == PlaceHolder::PEL)
47 {
48 if (i_pelTuple)
49 {
50 // LOG PEL
51 // This should call create PEL API from the event logger.
52 return;
53 }
54 std::cout << "Pel info tuple required to log PEL for message <" +
55 l_log.str() + ">"
56 << std::endl;
57 }
58 else if (i_placeHolder == PlaceHolder::VPD_WRITE)
59 {
60 if (!m_vpdWriteLogger)
61 {
62 m_vpdWriteLogger.reset(
63 new SyncFileLogger("/var/lib/vpd/vpdWrite.log", 128));
64 }
65 m_vpdWriteLogger->logMessage(l_log.str());
Alpana Kumari138489f2025-11-10 08:59:20 -060066 }
67 else
68 {
Souvik Roy2f390432025-11-14 08:07:04 +000069 // Default case, let it go to journal.
70 std::cout << l_log.str() << std::endl;
Alpana Kumari138489f2025-11-10 08:59:20 -060071 }
Sunny Srivastava5779d972025-08-08 01:45:23 -050072 }
Souvik Roy2f390432025-11-14 08:07:04 +000073 catch (const std::exception& l_ex)
Sunny Srivastava5779d972025-08-08 01:45:23 -050074 {
Souvik Roy2f390432025-11-14 08:07:04 +000075 std::cout << "Failed to log message:[" + l_log.str() +
76 "]. Error: " + std::string(l_ex.what())
Sunny Srivastava5779d972025-08-08 01:45:23 -050077 << std::endl;
78 }
Sunny Srivastava5779d972025-08-08 01:45:23 -050079}
80
Alpana Kumari138489f2025-11-10 08:59:20 -060081#ifdef ENABLE_FILE_LOGGING
Souvik Roya5e18b82025-09-25 05:59:56 +000082void Logger::initiateVpdCollectionLogging() noexcept
83{
84 try
85 {
Souvik Roy8042bbf2025-10-06 09:16:50 +000086 // collection log file directory
87 const std::filesystem::path l_collectionLogDirectory{"/var/lib/vpd"};
88
89 std::error_code l_ec;
90 if (!std::filesystem::exists(l_collectionLogDirectory, l_ec))
91 {
92 if (l_ec)
93 {
94 throw std::runtime_error(
95 "File system call to exist failed with error = " +
96 l_ec.message());
97 }
98 throw std::runtime_error(
99 "Directory " + l_collectionLogDirectory.string() +
100 " does not exist");
101 }
102
103 // base name of collection log file
104 std::filesystem::path l_collectionLogFilePath{l_collectionLogDirectory};
105 l_collectionLogFilePath /= "collection";
106
107 unsigned l_collectionLogFileCount{0};
108
109 std::filesystem::file_time_type l_oldestFileTime;
110 std::filesystem::path l_oldestFilePath{l_collectionLogFilePath};
111
112 // iterate through all entries in the log directory
113 for (const auto& l_dirEntry :
114 std::filesystem::directory_iterator(l_collectionLogDirectory))
115 {
116 // check /var/lib/vpd for number "collection.*" log file
117 const std::regex l_collectionLogFileRegex{"collection.*\\.log"};
118
119 if (std::filesystem::is_regular_file(l_dirEntry.path()) &&
120 std::regex_match(l_dirEntry.path().filename().string(),
121 l_collectionLogFileRegex))
122 {
123 // check the write time of this file
124 const auto l_fileWriteTime =
125 std::filesystem::last_write_time(l_dirEntry.path());
126
127 // update oldest file path if required
128 if (l_fileWriteTime < l_oldestFileTime)
129 {
130 l_oldestFileTime = l_fileWriteTime;
131 l_oldestFilePath = l_dirEntry.path();
132 }
133
134 l_collectionLogFileCount++;
135 }
136 }
137
138 // maximum number of collection log files to maintain
139 constexpr auto l_maxCollectionLogFiles{3};
140
141 if (l_collectionLogFileCount >= l_maxCollectionLogFiles)
142 {
143 // delete oldest collection log file
144 l_collectionLogFilePath = l_oldestFilePath;
145
146 logMessage("Deleting collection log file " +
147 l_collectionLogFilePath.string());
148
149 std::error_code l_ec;
150 if (!std::filesystem::remove(l_collectionLogFilePath, l_ec))
151 {
152 logMessage("Failed to delete existing collection log file " +
153 l_collectionLogFilePath.string() +
154 " Error: " + l_ec.message());
155 }
156 }
157 else
158 {
159 l_collectionLogFilePath +=
160 "_" + std::to_string(l_collectionLogFileCount) + ".log";
161 }
162
163 // create collection logger object with collection_(n+1).log
Souvik Roy0fb5c3b2025-09-15 08:18:25 +0000164 m_collectionLogger.reset(
Souvik Roy8042bbf2025-10-06 09:16:50 +0000165 new AsyncFileLogger(l_collectionLogFilePath, 4096));
Souvik Roya5e18b82025-09-25 05:59:56 +0000166 }
167 catch (const std::exception& l_ex)
168 {
169 logMessage("Failed to initialize collection logger. Error: " +
170 std::string(l_ex.what()));
171 }
172}
Alpana Kumari138489f2025-11-10 08:59:20 -0600173#endif
Souvik Roya5e18b82025-09-25 05:59:56 +0000174
Souvik Roy6bd74ad2025-09-12 06:24:06 +0000175void SyncFileLogger::logMessage(const std::string_view& i_message)
176{
177 try
178 {
Souvik Royd834b122025-10-28 06:37:51 +0000179 if (m_currentNumEntries >= m_maxEntries)
Souvik Roy6bd74ad2025-09-12 06:24:06 +0000180 {
181 rotateFile();
182 }
Souvik Royd834b122025-10-28 06:37:51 +0000183
184 std::string l_timeStampedMsg{
185 timestamp() + " : " + std::string(i_message)};
186
187 // check size of message and pad/trim as required
188 if (l_timeStampedMsg.length() > m_logEntrySize)
189 {
190 l_timeStampedMsg.resize(m_logEntrySize);
191 }
192 else if (l_timeStampedMsg.length() < m_logEntrySize)
193 {
194 constexpr char l_padChar{' '};
195 l_timeStampedMsg.append(m_logEntrySize - l_timeStampedMsg.length(),
196 l_padChar);
197 }
198
199 // write the message to file
200 m_fileStream << l_timeStampedMsg << std::endl;
201
202 // increment number of entries only if write to file is successful
203 ++m_currentNumEntries;
Souvik Roy6bd74ad2025-09-12 06:24:06 +0000204 }
205 catch (const std::exception& l_ex)
206 {
207 // log message to journal if we fail to log to file
208 auto l_logger = Logger::getLoggerInstance();
209 l_logger->logMessage(i_message);
210 }
211}
212
Souvik Royf8587362025-09-25 09:56:20 +0000213void AsyncFileLogger::logMessage(const std::string_view& i_message)
Souvik Roy0fb5c3b2025-09-15 08:18:25 +0000214{
215 try
216 {
Souvik Royf8587362025-09-25 09:56:20 +0000217 // acquire lock on queue
218 std::unique_lock<std::mutex> l_lock(m_mutex);
219
220 // push message to queue
221 m_messageQueue.emplace(timestamp() + " : " + std::string(i_message));
222
223 // notify log worker thread
224 m_cv.notify_one();
Souvik Roy0fb5c3b2025-09-15 08:18:25 +0000225 }
226 catch (const std::exception& l_ex)
227 {
Souvik Royf8587362025-09-25 09:56:20 +0000228 // log message to journal if we fail to push message to queue
229 Logger::getLoggerInstance()->logMessage(i_message);
Souvik Roy0fb5c3b2025-09-15 08:18:25 +0000230 }
231}
232
233void AsyncFileLogger::fileWorker() noexcept
234{
Souvik Royf8587362025-09-25 09:56:20 +0000235 // create lock object on mutex
236 std::unique_lock<std::mutex> l_lock(m_mutex);
237
238 // infinite loop
239 while (true)
240 {
241 // check for exit conditions
242 if (!m_fileStream.is_open() || m_stopLogging)
243 {
244 break;
245 }
246
247 // wait for notification from log producer
248 m_cv.wait(l_lock,
249 [this] { return m_stopLogging || !m_messageQueue.empty(); });
250
251 // flush the queue
252 while (!m_messageQueue.empty())
253 {
254 // read the first message in queue
255 const auto l_logMessage = m_messageQueue.front();
256 try
257 {
258 // pop the message from queue
259 m_messageQueue.pop();
260
261 // unlock mutex on queue
262 l_lock.unlock();
263
Souvik Royf8587362025-09-25 09:56:20 +0000264 // flush the message to file
265 m_fileStream << l_logMessage << std::endl;
266
267 // lock mutex on queue
268 l_lock.lock();
269 }
270 catch (const std::exception& l_ex)
271 {
272 // log message to journal if we fail to push message to queue
273 Logger::getLoggerInstance()->logMessage(l_logMessage);
274
275 // check if we need to reacquire lock before continuing to flush
276 // queue
277 if (!l_lock.owns_lock())
278 {
279 l_lock.lock();
280 }
281 }
282 } // queue flush loop
283 } // thread loop
Souvik Roy0fb5c3b2025-09-15 08:18:25 +0000284}
285
Souvik Roybac8ba62025-10-27 09:07:06 +0000286ILogFileHandler::ILogFileHandler(const std::filesystem::path& i_filePath,
287 const size_t i_maxEntries) :
288 m_filePath{i_filePath}, m_maxEntries{i_maxEntries}
289{
290 // check if log file already exists
291 std::error_code l_ec;
292 const bool l_logFileExists = std::filesystem::exists(m_filePath, l_ec);
293 if (l_ec)
294 {
295 Logger::getLoggerInstance()->logMessage(
296 "Failed to check if log file already exists. Error: " +
297 l_ec.message());
298 }
299
Souvik Royb89c2c72025-11-12 06:07:49 +0000300 if (!l_logFileExists)
301 {
302 l_ec.clear();
303
304 // check if the parent directory of the file exists
305 if (!std::filesystem::exists(m_filePath.parent_path(), l_ec))
306 {
307 if (l_ec)
308 {
309 Logger::getLoggerInstance()->logMessage(
310 "Failed to check if log file parent directory [" +
311 m_filePath.parent_path().string() +
312 "] exists. Error: " + l_ec.message());
313
314 l_ec.clear();
315 }
316
317 // create parent directories
318 if (!std::filesystem::create_directories(m_filePath.parent_path(),
319 l_ec))
320 {
321 if (l_ec)
322 {
323 throw std::runtime_error(
324 "Failed to create parent directory of log file path:[" +
325 m_filePath.string() + "]. Error: " + l_ec.message());
326 }
327 }
328 }
329 }
330
Souvik Roybac8ba62025-10-27 09:07:06 +0000331 // enable exception mask to throw on badbit and failbit
332 m_fileStream.exceptions(std::ios_base::badbit | std::ios_base::failbit);
Souvik Roy2f390432025-11-14 08:07:04 +0000333 // open the file in append mode
334 m_fileStream.open(m_filePath, std::ios::out | std::ios::ate);
Souvik Roybac8ba62025-10-27 09:07:06 +0000335
336 if (l_logFileExists)
337 {
338 // log file already exists, check and update the number of entries
339 std::ifstream l_readFileStream{m_filePath};
340 for (std::string l_line; std::getline(l_readFileStream, l_line);
341 ++m_currentNumEntries)
342 {}
343
344 l_readFileStream.close();
345 }
346}
347
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500348namespace logging
349{
350void logMessage(std::string_view message, const std::source_location& location)
351{
352 std::ostringstream log;
353 log << "FileName: " << location.file_name() << ","
354 << " Line: " << location.line() << " " << message;
355
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500356 std::cout << log.str() << std::endl;
357}
358} // namespace logging
359} // namespace vpd