Support adding sinks to logging (no default stdout now)
This commit is contained in:
parent
22ef7b45a8
commit
19e0d1a044
3 changed files with 24 additions and 5 deletions
|
|
@ -5,4 +5,4 @@ file(GLOB_RECURSE PSEMEK_LOG_SOURCES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "sou
|
|||
|
||||
psemek_add_library(psemek-log ${PSEMEK_LOG_HEADERS} ${PSEMEK_LOG_SOURCES})
|
||||
target_include_directories(psemek-log PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(psemek-log PUBLIC ${CMAKE_THREAD_LIBS_INIT})
|
||||
target_link_libraries(psemek-log PUBLIC psemek-io ${CMAKE_THREAD_LIBS_INIT})
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
#pragma once
|
||||
|
||||
#include <psemek/log/level.hpp>
|
||||
#include <psemek/io/stream.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
|
@ -34,6 +35,8 @@ namespace psemek::log
|
|||
std::thread::id id_;
|
||||
};
|
||||
|
||||
void add_sink(std::unique_ptr<io::ostream> stream, level l);
|
||||
|
||||
void put_message(level l, std::string const & message);
|
||||
|
||||
struct log_stream
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@
|
|||
#include <unordered_map>
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
#include <vector>
|
||||
|
||||
namespace psemek::log
|
||||
{
|
||||
|
|
@ -18,6 +19,9 @@ namespace psemek::log
|
|||
static std::mutex thread_names_mutex;
|
||||
static std::unordered_map<std::thread::id, std::string> thread_names;
|
||||
|
||||
static std::mutex sinks_mutex;
|
||||
static std::vector<std::pair<std::unique_ptr<io::ostream>, level>> sinks;
|
||||
|
||||
static void put_message(level l, std::string const & message, std::string const & thread_name);
|
||||
|
||||
void register_thread(std::string name)
|
||||
|
|
@ -87,11 +91,23 @@ namespace psemek::log
|
|||
<< '[' << 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(7) << l << ']'
|
||||
<< ' ' << message;
|
||||
<< ' ' << message << '\n';
|
||||
|
||||
static std::mutex cout_mutex;
|
||||
std::lock_guard lock{cout_mutex};
|
||||
std::cout << os.str() << std::endl;
|
||||
auto const str = os.str();
|
||||
|
||||
std::lock_guard lock{sinks_mutex};
|
||||
|
||||
for (auto const & sink : sinks)
|
||||
{
|
||||
if (static_cast<int>(l) >= static_cast<int>(sink.second))
|
||||
sink.first->write(str.data(), str.size());
|
||||
}
|
||||
}
|
||||
|
||||
void add_sink(std::unique_ptr<io::ostream> stream, level l)
|
||||
{
|
||||
std::lock_guard lock{sinks_mutex};
|
||||
sinks.push_back({std::move(stream), l});
|
||||
}
|
||||
|
||||
void put_message(level l, std::string const & message)
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue