Skip to content

Commit

Permalink
Improving hash for log once instances
Browse files Browse the repository at this point in the history
  • Loading branch information
nadrino committed Apr 7, 2023
1 parent c592711 commit b00922b
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
4 changes: 2 additions & 2 deletions include/Logger.h
Original file line number Diff line number Diff line change
Expand Up @@ -184,14 +184,14 @@ namespace {
static inline std::string _currentPrefix_{};
static inline std::string _outputFileName_{};
static inline std::mutex _loggerMutex_{};
static inline std::unordered_set<void*> _onceLogList_{};
static inline std::unordered_set<size_t> _onceLogList_{};
static inline Color _currentColor_{Logger::Color::RESET};
static inline LogLevel _currentLogLevel_{Logger::LogLevel::TRACE};
static inline LoggerUtils::StreamBufferSupervisor* _streamBufferSupervisorPtr_{nullptr};
static inline LoggerUtils::StreamBufferSupervisor _streamBufferSupervisor_;

// non-static
std::scoped_lock<std::mutex> _lock_{_loggerMutex_};
std::scoped_lock<std::mutex> _lock_{_loggerMutex_}; // one logger can be created at a given time
#else
// parameters
static bool _enableColors_;
Expand Down
6 changes: 4 additions & 2 deletions include/implementation/Logger.impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -209,14 +209,16 @@ namespace {
_currentLineNumber_ = lineNumber_;

if( once_ ){
if( _onceLogList_.find( reinterpret_cast<int *>( (int*) fileName_ - (int*) &lineNumber_ ) ) != _onceLogList_.end() ){
size_t instanceHash{(size_t) lineNumber_};
LoggerUtils::hashCombine(instanceHash, fileName_);
if( _onceLogList_.find( instanceHash ) != _onceLogList_.end() ){
// mute
Logger::_currentLogLevel_ = LogLevel::INVALID;
}
else{
// will be printed only this time:
// dirty trick (better way??): get unique identifier out of file name and lineNumber.
_onceLogList_.insert(reinterpret_cast<int *>( (int*) fileName_ - (int*) &lineNumber_ ) );
_onceLogList_.insert( instanceHash );
}
}
}
Expand Down
7 changes: 7 additions & 0 deletions include/implementation/LoggerUtils.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "thread"
#include "vector"
#include "string"
#include "functional"


#ifndef HAS_CPP_17
Expand Down Expand Up @@ -95,6 +96,12 @@ namespace LoggerUtils{
inline int getTerminalWidth();
inline std::string getExecutableName();

// hash Utils
template <class T> inline void hashCombine(std::size_t& seed, const T& v) {
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}

}

#include "LoggerUtils.impl.h"
Expand Down

0 comments on commit b00922b

Please sign in to comment.