Fix thread registration

This commit is contained in:
Nikita Lisitsa 2020-09-30 16:16:08 +03:00
parent 0073b8bfc9
commit 58a30fe347

View file

@ -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,14 +29,18 @@ namespace psemek::log
void register_thread(std::thread::id id, std::string name)
{
auto it = thread_names.find(id);
if (it != thread_names.end())
throw std::runtime_error("Thread \"" + name + "\" already registered!");
{
std::lock_guard lock{thread_names_mutex};
if (name.size() > max_thread_name_length)
throw std::runtime_error("Thread \"" + name + "\" name is too long");
auto it = thread_names.find(id);
if (it != thread_names.end())
throw std::runtime_error("Thread \"" + name + "\" already registered!");
thread_names[id] = name;
if (name.size() > max_thread_name_length)
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;