1
0
Fork 0
mirror of https://github.com/OpenMW/openmw.git synced 2025-04-01 12:06:41 +00:00

Acquire log lock only when logger should log

To minimize overhead for calls when level is less than current. For example
Log(Debug::Debug) should not lock mutex when current logging level is Verbose.
This commit is contained in:
elsid 2021-11-07 19:47:02 +01:00
parent 256ec4c752
commit 727f784a98
No known key found for this signature in database
GPG key ID: B845CB9FEE18AB40

View file

@ -29,25 +29,29 @@ class Log
std::unique_lock<std::mutex> mLock; std::unique_lock<std::mutex> mLock;
public: public:
// Locks a global lock while the object is alive explicit Log(Debug::Level level)
Log(Debug::Level level) : : mShouldLog(level <= Debug::CurrentDebugLevel)
mLock(sLock),
mLevel(level)
{ {
// No need to hold the lock if there will be no logging anyway
if (!mShouldLog)
return;
// Locks a global lock while the object is alive
mLock = std::unique_lock<std::mutex>(sLock);
// If the app has no logging system enabled, log level is not specified. // If the app has no logging system enabled, log level is not specified.
// Show all messages without marker - we just use the plain cout in this case. // Show all messages without marker - we just use the plain cout in this case.
if (Debug::CurrentDebugLevel == Debug::NoLevel) if (Debug::CurrentDebugLevel == Debug::NoLevel)
return; return;
if (mLevel <= Debug::CurrentDebugLevel) std::cout << static_cast<unsigned char>(level);
std::cout << static_cast<unsigned char>(mLevel);
} }
// Perfect forwarding wrappers to give the chain of objects to cout // Perfect forwarding wrappers to give the chain of objects to cout
template<typename T> template<typename T>
Log& operator<<(T&& rhs) Log& operator<<(T&& rhs)
{ {
if (mLevel <= Debug::CurrentDebugLevel) if (mShouldLog)
std::cout << std::forward<T>(rhs); std::cout << std::forward<T>(rhs);
return *this; return *this;
@ -55,12 +59,12 @@ public:
~Log() ~Log()
{ {
if (mLevel <= Debug::CurrentDebugLevel) if (mShouldLog)
std::cout << std::endl; std::cout << std::endl;
} }
private: private:
Debug::Level mLevel; const bool mShouldLog;
}; };
#endif #endif