FERS 1.0.0
The Flexible Extensible Radar Simulator
Loading...
Searching...
No Matches
logging.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: GPL-2.0-only
2//
3// Copyright (c) 2024-present FERS Contributors (see AUTHORS.md).
4//
5// See the GNU GPLv2 LICENSE file in the FERS project root for more information.
6
7/**
8 * @file logging.cpp
9 * @brief Implementation of the logging system.
10 */
11
12#include "logging.h"
13
14#include <chrono>
15#include <ctime>
16#include <filesystem>
17#include <iomanip>
18#include <iostream>
19#include <sstream>
20
21namespace logging
22{
24
25 std::string Logger::getCurrentTimestamp() noexcept
26 {
27 const auto now = std::chrono::system_clock::now();
28 const std::time_t time = std::chrono::system_clock::to_time_t(now);
29 std::tm tm{};
30 localtime_r(&time, &tm);
31
32 std::ostringstream oss;
33 oss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S");
34 return oss.str();
35 }
36
37 void Logger::log(const Level level, const std::string& message, const std::source_location& location) noexcept
38 {
39 if (level >= _log_level)
40 {
41 std::scoped_lock lock(_log_mutex);
42
43 const std::string filename = std::filesystem::path(location.file_name()).filename().string();
44 const std::string file_line = filename + ":" + std::to_string(location.line());
45
46 std::ostringstream oss;
47 oss << "[" << getCurrentTimestamp() << "] " << "[" << std::setw(7) << std::left << getLevelString(level)
48 << "] " << "[" << std::setw(30) << std::left << file_line << "] " << message << std::endl;
49
50 std::cerr << oss.str();
51
52 if (_log_file && _log_file->is_open())
53 {
54 *_log_file << oss.str();
55 }
56 }
57 }
58
59 std::expected<void, std::string> Logger::logToFile(const std::string& filePath) noexcept
60 {
61 std::scoped_lock lock(_log_mutex);
62
63 std::ofstream file(filePath, std::ios::out | std::ios::trunc);
64 if (!file)
65 {
66 return std::unexpected("Unable to open log file: " + filePath);
67 }
68
69 _log_file = std::move(file);
70 return {};
71 }
72}
Enum class representing the log levels.
Thread-safe logger class for handling logging operations.
Definition logging.h:50
void log(Level level, const std::string &message, const std::source_location &location=std::source_location::current()) noexcept
Logs a message with a specific log level and source location.
Definition logging.cpp:37
std::expected< void, std::string > logToFile(const std::string &filePath) noexcept
Sets the log file path to log messages to a file.
Definition logging.cpp:59
Header file for the logging system.
std::string getLevelString(const Level level) noexcept
Converts a log level enum value to its string representation.
Definition logging.h:121
Logger logger
Externally available logger object.
Definition logging.cpp:23