game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
logger.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// logger.h
4// ==============================================================================
5// Centralized logging system with levels and optional file output
6// ==============================================================================
7// This provides a singleton logger that replaces direct std::cout/std::cerr
8// usage throughout the codebase. Features:
9// - Log levels (DEBUG, INFO, WARN, ERROR, FATAL)
10// - Optional file output
11// - Thread-safe logging
12// - Configurable verbosity
13// - Automatic timestamping
14//
15// ## Usage Example
16// @code
17// Logger::info("Starting application");
18// Logger::warn("Configuration file not found, using defaults");
19// Logger::error("Failed to connect to Steam: {}", errorMsg);
20// Logger::debug("Game library contains {} games", gameCount);
21// @endcode
22// ==============================================================================
23
24#pragma once
25
26#include <fstream>
27#include <iostream>
28#include <mutex>
29#include <sstream>
30#include <string>
31
32// ==============================================================================
33// Log Levels
34// ==============================================================================
35
36enum class LogLevel
37{
38 DEBUG = 0, ///< Verbose debugging information
39 INFO = 1, ///< General informational messages
40 WARN = 2, ///< Warning messages (non-critical issues)
41 ERROR = 3, ///< Error messages (recoverable failures)
42 FATAL = 4 ///< Fatal errors (application will terminate)
43};
44
45// ==============================================================================
46// Logger Class (Singleton)
47// ==============================================================================
48
49/**
50 * @class Logger
51 * @brief Thread-safe logging system with levels and optional file output
52 *
53 * Singleton pattern ensures consistent logging across entire application.
54 * All methods are static for convenient usage without getInstance() calls.
55 */
56class Logger
57{
58 public:
59 // ==========================================================================
60 // Initialization & Configuration
61 // ==========================================================================
62
63 /**
64 * @brief Initialize logger with optional file output
65 * @param logFilePath Path to log file (empty = console only)
66 * @param minLevel Minimum log level to output (default: INFO)
67 */
68 static void init(const std::string& logFilePath = "", LogLevel minLevel = LogLevel::INFO);
69
70 /**
71 * @brief Set minimum log level
72 * @param level Messages below this level will be ignored
73 */
74 static void setLogLevel(LogLevel level);
75
76 /**
77 * @brief Enable or disable console output
78 * @param enabled If false, only logs to file (if configured)
79 */
80 static void setConsoleOutput(bool enabled);
81
82 /**
83 * @brief Enable or disable timestamps in log messages
84 * @param enabled If true, prepends timestamp to each message
85 */
86 static void setTimestamps(bool enabled);
87
88 /**
89 * @brief Shutdown logger and close log file
90 */
91 static void shutdown();
92
93 // ==========================================================================
94 // Logging Methods
95 // ==========================================================================
96
97 /**
98 * @brief Log debug message (verbose development info)
99 */
100 template <typename... Args> static void debug(const std::string& message, Args&&... args)
101 {
102 log(LogLevel::DEBUG, format(message, std::forward<Args>(args)...));
103 }
104
105 /**
106 * @brief Log info message (general information)
107 */
108 template <typename... Args> static void info(const std::string& message, Args&&... args)
109 {
110 log(LogLevel::INFO, format(message, std::forward<Args>(args)...));
111 }
112
113 /**
114 * @brief Log warning message (non-critical issue)
115 */
116 template <typename... Args> static void warn(const std::string& message, Args&&... args)
117 {
118 log(LogLevel::WARN, format(message, std::forward<Args>(args)...));
119 }
120
121 /**
122 * @brief Log error message (recoverable failure)
123 */
124 template <typename... Args> static void error(const std::string& message, Args&&... args)
125 {
126 log(LogLevel::ERROR, format(message, std::forward<Args>(args)...));
127 }
128
129 /**
130 * @brief Log fatal error message (application will terminate)
131 */
132 template <typename... Args> static void fatal(const std::string& message, Args&&... args)
133 {
134 log(LogLevel::FATAL, format(message, std::forward<Args>(args)...));
135 }
136
137 private:
138 // ==========================================================================
139 // Private Implementation
140 // ==========================================================================
141
142 Logger() = default;
143 ~Logger() = default;
144 Logger(const Logger&) = delete;
145 Logger& operator=(const Logger&) = delete;
146
147 static Logger& instance()
148 {
149 static Logger instance;
150 return instance;
151 }
152
153 static void log(LogLevel level, const std::string& message);
154 static std::string getLevelString(LogLevel level);
155 static std::string getCurrentTimestamp();
156
157 // Simple formatting - replaces {} with arguments
158 template <typename T> static std::string format(const std::string& fmt, T&& arg)
159 {
160 size_t pos = fmt.find("{}");
161 if (pos == std::string::npos)
162 {
163 return fmt;
164 }
165
166 std::ostringstream oss;
167 oss << arg;
168
169 std::string result = fmt;
170 result.replace(pos, 2, oss.str());
171 return result;
172 }
173
174 template <typename T, typename... Args>
175 static std::string format(const std::string& fmt, T&& first, Args&&... rest)
176 {
177 std::string result = format(fmt, std::forward<T>(first));
178 return format(result, std::forward<Args>(rest)...);
179 }
180
181 static std::string format(const std::string& fmt)
182 {
183 return fmt;
184 }
185
186 // ==========================================================================
187 // Member Variables
188 // ==========================================================================
189
190 std::mutex logMutex_;
191 std::ofstream logFile_;
192 LogLevel minLevel_ = LogLevel::INFO;
193 bool consoleOutput_ = true;
194 bool timestamps_ = true;
195};
Thread-safe logging system with levels and optional file output.
Definition logger.h:57
static void setLogLevel(LogLevel level)
Set minimum log level.
Definition logger.cpp:41
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
Definition logger.h:100
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
static void setConsoleOutput(bool enabled)
Enable or disable console output.
Definition logger.cpp:48
static void shutdown()
Shutdown logger and close log file.
Definition logger.cpp:62
static void fatal(const std::string &message, Args &&... args)
Log fatal error message (application will terminate).
Definition logger.h:132
static void setTimestamps(bool enabled)
Enable or disable timestamps in log messages.
Definition logger.cpp:55
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
static void init(const std::string &logFilePath="", LogLevel minLevel=LogLevel::INFO)
Initialize logger with optional file output.
Definition logger.cpp:17
LogLevel
Definition logger.h:37
@ FATAL
Fatal errors (application will terminate).
Definition logger.h:42
@ WARN
Warning messages (non-critical issues).
Definition logger.h:40
@ INFO
General informational messages.
Definition logger.h:39
@ ERROR
Error messages (recoverable failures).
Definition logger.h:41
@ DEBUG
Verbose debugging information.
Definition logger.h:38