mutex
This commit is contained in:
parent
87d63150ab
commit
9ea5878a23
22
Log.cpp
22
Log.cpp
|
@ -6,6 +6,10 @@
|
|||
#include <iostream> // std::ostream, std::cout, std::cin
|
||||
#include <vector> // list of outputs
|
||||
|
||||
#if LOG_USEMUTEX == 1
|
||||
#include <mutex>
|
||||
#endif
|
||||
|
||||
namespace Log {
|
||||
|
||||
/*
|
||||
|
@ -21,6 +25,11 @@ public:
|
|||
virtual ~Output() {}
|
||||
|
||||
virtual void log(Level lvl, std::stringbuf* sbuf) {
|
||||
//aquire lock
|
||||
#if LOG_USEMUTEX == 1
|
||||
std::unique_lock<std::mutex> lock(ostreamLock);
|
||||
#endif
|
||||
|
||||
std::ostream* os = getOs(lvl);
|
||||
if (os) {
|
||||
*os << sbuf << std::endl;
|
||||
|
@ -34,6 +43,10 @@ protected:
|
|||
// returns the correct ostream for the given log-level
|
||||
// or returns nullptr if no ostream is set/enabled for this level
|
||||
virtual std::ostream* getOs(Level lvl) = 0; // abstract
|
||||
|
||||
#if LOG_USEMUTEX == 1
|
||||
std::mutex ostreamLock; //used for both streams
|
||||
#endif
|
||||
};
|
||||
|
||||
// logging to stdout/stderr
|
||||
|
@ -56,6 +69,11 @@ private:
|
|||
// OFF FATAL ERROR WARN NOTE INFO DEBUG TRACE
|
||||
static const char* color_codes[] = {"", "1;31;40m", "31m", "33m", "96m", "32m", "0m", "0m"};
|
||||
|
||||
//aquire lock
|
||||
#if LOG_USEMUTEX == 1
|
||||
std::unique_lock<std::mutex> lock(ostreamLock);
|
||||
#endif
|
||||
|
||||
std::ostream* os = getOs(lvl);
|
||||
|
||||
if (os) {
|
||||
|
@ -98,6 +116,10 @@ private:
|
|||
std::ofstream ofs;
|
||||
Level lvl_min = FATAL;
|
||||
|
||||
#if LOG_USEMUTEX == 1
|
||||
std::mutex ostreamLock; //used for both streams
|
||||
#endif
|
||||
|
||||
virtual std::ostream* getOs(Level lvl) {
|
||||
if (lvl_min <= lvl && lvl <= lvl_max)
|
||||
return &ofs;
|
||||
|
|
6
Log.h
6
Log.h
|
@ -3,6 +3,10 @@
|
|||
#include <sstream> // std::stringstream (buffer for log entries)
|
||||
#include <string>
|
||||
|
||||
#ifndef LOG_USEMUTEX
|
||||
#define LOG_USEMUTEX 1
|
||||
#endif
|
||||
|
||||
namespace Log {
|
||||
enum Level { OFF = 0, FATAL, ERROR, WARN, NOTE, INFO, DEBUG, TRACE };
|
||||
|
||||
|
@ -17,6 +21,8 @@ void addLogfile(const std::string& filename, Level min, Level max);
|
|||
void setConsoleLogLevel(Level lvl);
|
||||
void setColoredOutput(bool enabled);
|
||||
|
||||
inline bool useMutex() { return LOG_USEMUTEX; }
|
||||
|
||||
// Log entry that can be formed with various mixed data types
|
||||
// by concatenation with the << operator
|
||||
// Inspired from https://stackoverflow.com/a/8337882
|
||||
|
|
Loading…
Reference in New Issue