IOStream
-
class ThreadSafeIOStream
A thread-safe version of I/O stream.
The
ThreadSafeIOStreamclass provides thread-safe output capabilities by locking a mutex during output operations. It allows users to set a prefix for output messages, which can help debug and monitor applications with multiple threads.Note
The stream will only be outputed when the
std::endlmanipulator is founded, indicating that the line ended.Public Functions
-
ThreadSafeIOStream()
Constructs a ThreadSafeIOStream.
-
void setPrefix(const std::string &prefix)
Sets the prefix printed in front of each output line.
- Parameters:
prefix – The prefix string to prepend to the output.
-
ThreadSafeIOStream &operator<<(std::ostream &(*manip)(std::ostream&))
Handles the
std::endlmanipulator for proper line breaks.This function flushes the thread-local buffer to the shared
std::coutunder a mutex lock whenstd::endlis encountered.- Parameters:
manip – A pointer to a manipulator function such as
std::endl.- Returns:
A reference to
ThreadSafeIOStreamfor chaining.
-
template<typename T>
inline ThreadSafeIOStream &operator<<(const T &value) Output operator overload to handle various types.
This function writes to a thread-local buffer and flushes it only when a newline is encountered.
- Template Parameters:
T – The type of value to output.
- Parameters:
value – The value to output.
- Returns:
A reference to
ThreadSafeIOStreamfor chaining.
-
template<typename T>
inline ThreadSafeIOStream &operator>>(T &value) Input operator overload to handle various types.
This function locks a mutex to ensure thread-safe input operations. The prefix will be appended before the input (not always a
line)- Template Parameters:
T – The type of value to read.
- Parameters:
value – The variable to store the input.
- Returns:
A reference to
ThreadSafeIOStreamfor chaining.
Private Members
-
std::mutex global_mutex_
Mutex to ensure thread-safe access to std::cout.
-
ThreadSafeIOStream()
-
class Logger
A flexible, thread-safe logger that supports logging to any stream.
Public Functions
-
Logger(std::ostream &stream)
Constructs a Logger with a specified output stream.
- Parameters:
stream – The initial output stream.
-
void log(LogLevel level, const std::string &message)
Logs a message with the specified log level.
- Parameters:
level – The log level.
message – The message to log.
-
void setLogLevel(LogLevel level)
Sets the minimum log level. Messages below this level will not be logged.
- Parameters:
level – The minimum log level.
Private Functions
-
std::string levelToString(LogLevel level) const
Converts a log level to its string representation.
- Parameters:
level – The log level.
- Returns:
The string representation of the log level.
-
std::string getTimestamp() const
Gets the current timestamp as a string.
- Returns:
The timestamp string in the format “YYYY-MM-DD HH:MM:SS”.
-
Logger(std::ostream &stream)