Fix thread registration
This commit is contained in:
parent
0073b8bfc9
commit
58a30fe347
1 changed files with 22 additions and 9 deletions
|
|
@ -19,6 +19,7 @@ namespace psemek::log
|
|||
max_thread_name_length = length;
|
||||
}
|
||||
|
||||
static std::mutex thread_names_mutex;
|
||||
static std::unordered_map<std::thread::id, std::string> thread_names;
|
||||
|
||||
void register_thread(std::string name)
|
||||
|
|
@ -28,6 +29,9 @@ namespace psemek::log
|
|||
|
||||
void register_thread(std::thread::id id, std::string name)
|
||||
{
|
||||
{
|
||||
std::lock_guard lock{thread_names_mutex};
|
||||
|
||||
auto it = thread_names.find(id);
|
||||
if (it != thread_names.end())
|
||||
throw std::runtime_error("Thread \"" + name + "\" already registered!");
|
||||
|
|
@ -36,6 +40,7 @@ namespace psemek::log
|
|||
throw std::runtime_error("Thread \"" + name + "\" name is too long");
|
||||
|
||||
thread_names[id] = name;
|
||||
}
|
||||
|
||||
put_message(level::info, "Thread \"" + name + "\" registered");
|
||||
}
|
||||
|
|
@ -59,14 +64,22 @@ namespace psemek::log
|
|||
auto const millis = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now().time_since_epoch()).count() % 1000;
|
||||
|
||||
auto const id = std::this_thread::get_id();
|
||||
auto const it = thread_names.find(id);
|
||||
|
||||
auto const & thread_name = (it == thread_names.end()) ? unknown_thread_name : it->second;
|
||||
|
||||
std::string const * thread_name;
|
||||
{
|
||||
std::lock_guard lock{thread_names_mutex};
|
||||
auto const it = thread_names.find(id);
|
||||
if (it == thread_names.end())
|
||||
thread_name = &unknown_thread_name;
|
||||
else
|
||||
thread_name = &(it->second);
|
||||
}
|
||||
|
||||
std::ostringstream os;
|
||||
os
|
||||
<< '[' << std::put_time(&tm, "%Y %b %d %H:%M:%S.") << std::setw(3) << std::setfill('0') << millis << ']'
|
||||
<< '[' << std::setw(max_thread_name_length) << std::setfill(' ') << thread_name << ']'
|
||||
<< '[' << std::setw(max_thread_name_length) << std::setfill(' ') << *thread_name << ']'
|
||||
<< '[' << std::setw(7) << l << ']'
|
||||
<< ' ' << message;
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue