17#include "configurer.h"
19#include <cci_configuration>
23#include <nonstd/optional.hpp>
24#include <spdlog/async.h>
25#include <spdlog/sinks/basic_file_sink.h>
26#include <spdlog/sinks/stdout_color_sinks.h>
27#include <spdlog/spdlog.h>
28#include <sysc/kernel/sc_status.h>
30#include <unordered_map>
31#include <util/logging.h>
33#include <boost/stacktrace.hpp>
37#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
38#if GCC_VERSION < 40900
41#define likely(x) __builtin_expect(x, 1)
42#define unlikely(x) __builtin_expect(x, 0)
57using namespace sc_core;
61struct char_equal_to :
public std::equal_to<char const*> {
62 bool operator()(
char const* __x,
char const* __y)
const {
return strcmp(__x, __y) == 0; }
67 uint64_t operator()(
char const* str)
const {
68 constexpr unsigned int seed = 131;
71 hash = (hash * seed) + (*str);
78 std::unordered_map<char const*, sc_core::sc_verbosity, char_hash, char_equal_to> table;
79 std::deque<std::string> cache;
83 std::tuple<bool, sc_core::sc_verbosity> get(
char const* key) {
84 std::lock_guard<std::mutex> lock(mtx);
85 auto it = table.find(key);
87 return {
true, it->second};
89 return {
false, sc_core::SC_DEBUG};
91 void insert(
char const* key, sc_core::sc_verbosity verb) {
92 std::lock_guard<std::mutex> lock(mtx);
93 cache.emplace_back(key);
94 table.insert({cache.back().c_str(), verb});
97 std::lock_guard<std::mutex> lock(mtx);
103static const cci::cci_originator originator;
105static const cci::cci_originator originator(
"reporting");
108bool& inst_based_logging() {
109 thread_local bool active = getenv(
"SCC_DISABLE_INSTANCE_BASED_LOGGING") ==
nullptr;
114 shared_ptr<spdlog::logger> file_logger;
115 shared_ptr<spdlog::logger> console_logger;
117 regex_t start_state{};
121 sc_time cycle_base{0, SC_NS};
122 auto operator=(
const scc::LogConfig& o) -> ExtLogConfig& {
123 scc::LogConfig::operator=(o);
126 auto match(
const char* type) ->
bool {
128 return regexec(&start_state, type, 0,
nullptr, 0) == 0;
130 return regex_search(type, reg_ex);
133 bool initialized{
false};
135 nonstd::optional<cci::cci_broker_handle> broker;
138auto get_tuple(
const sc_time& t) -> tuple<sc_time::value_type, sc_time_unit> {
139 auto val = t.value();
140 auto tr = (uint64_t)(sc_time::from_value(1).to_seconds() * 1E15);
142 while((tr % 10) == 0) {
149 while(tu < SC_SEC && (val % 10) == 0) {
152 tu += (0 == (scale % 3));
154 for(scale %= 3; scale != 0; scale--)
156 return make_tuple(val,
static_cast<sc_time_unit
>(tu));
159auto time2string(
const sc_time& t) ->
string {
160 const array<const char*, 6> time_units{
"fs",
"ps",
"ns",
"us",
"ms",
"s "};
161 const array<uint64_t, 6> multiplier{
162 1ULL, 1000ULL, 1000ULL * 1000, 1000ULL * 1000 * 1000, 1000ULL * 1000 * 1000 * 1000, 1000ULL * 1000 * 1000 * 1000 * 1000};
167 const auto tt = get_tuple(t);
168 const auto val = get<0>(tt);
169 const auto scale = get<1>(tt);
170 const auto fs_val = val * multiplier[scale];
171 for(
int j = multiplier.size() - 1; j >= scale; --j) {
172 if(fs_val >= multiplier[j]) {
173 const auto i = val / multiplier[j - scale];
174 const auto f = val % multiplier[j - scale];
175 oss << i <<
'.' << setw(3 * (j - scale)) << setfill(
'0') << right << f <<
' ' << time_units[j];
182auto compose_message(
const sc_report& rep,
const scc::LogConfig& cfg) ->
const string {
183 if(rep.get_severity() > SC_INFO || cfg.log_filter_regex.length() == 0 || rep.get_verbosity() == sc_core::SC_MEDIUM ||
184 log_cfg.match(rep.get_msg_type())) {
186 if(unlikely(cfg.print_sys_time))
188 if(likely(cfg.print_sim_time)) {
189 if(unlikely(log_cfg.cycle_base.value())) {
190 if(unlikely(cfg.print_delta))
191 os <<
"[" << std::setw(7) << std::setfill(
' ') << sc_time_stamp().value() / log_cfg.cycle_base.value() <<
"(" << setw(5)
192 << sc_delta_count() <<
")]";
194 os <<
"[" << std::setw(7) << std::setfill(
' ') << sc_time_stamp().value() / log_cfg.cycle_base.value() <<
"]";
196 auto t = time2string(sc_time_stamp());
197 if(unlikely(cfg.print_delta))
198 os <<
"[" << std::setw(20) << std::setfill(
' ') << t <<
"(" << setw(5) << sc_delta_count() <<
")]";
200 os <<
"[" << std::setw(20) << std::setfill(
' ') << t <<
"]";
203 if(unlikely(rep.get_id() >= 0))
205 <<
"IWEF"[rep.get_severity()] << rep.get_id() <<
") " << rep.get_msg_type() <<
": ";
206 else if(cfg.msg_type_field_width) {
207 if(cfg.msg_type_field_width == std::numeric_limits<unsigned>::max())
208 os <<
" " << rep.get_msg_type() <<
": ";
210 os <<
" " <<
util::padded(rep.get_msg_type(), cfg.msg_type_field_width) <<
": ";
214 if(rep.get_severity() > SC_INFO) {
215 if(rep.get_line_number())
216 os <<
"\n [FILE:" << rep.get_file_name() <<
":" << rep.get_line_number() <<
"]";
217 sc_simcontext* simc = sc_get_curr_simcontext();
218 if(simc && sc_is_running()) {
219 const char* proc_name = rep.get_process_name();
221 os <<
"\n [PROCESS:" << proc_name <<
"]";
229inline void log2logger(spdlog::logger& logger,
const sc_report& rep,
const scc::LogConfig& cfg) {
230 auto msg = compose_message(rep, cfg);
233 switch(rep.get_severity()) {
235 switch(rep.get_verbosity()) {
253#ifdef WITH_STACKTRACE
254 if(getenv(
"SCC_PRINT_STACK_ON_ERROR"))
255 logger.error(boost::stacktrace::to_string(boost::stacktrace::stacktrace()));
259 logger.critical(msg);
260#ifdef WITH_STACKTRACE
261 if(getenv(
"SCC_PRINT_STACK_ON_ERROR"))
262 logger.error(boost::stacktrace::to_string(boost::stacktrace::stacktrace()));
270inline void flush_loggers() {
271 log_cfg.console_logger->flush();
272 if(log_cfg.file_logger)
273 log_cfg.file_logger->flush();
276void report_handler(
const sc_report& rep,
const sc_actions& actions) {
277 thread_local bool sc_stop_called =
false;
278 if(actions & SC_DO_NOTHING)
280 if(rep.get_severity() == sc_core::SC_INFO || !log_cfg.report_only_first_error || sc_report_handler::get_count(SC_ERROR) < 2) {
281 if((actions & SC_DISPLAY) && (!log_cfg.file_logger || rep.get_verbosity() < SC_HIGH))
283 log2logger(*log_cfg.console_logger, rep, log_cfg);
284 }
catch(
const spdlog::spdlog_ex& e) {
286 if((actions & SC_LOG) && log_cfg.file_logger) {
288 lcfg.print_sim_time =
true;
289 if(!lcfg.msg_type_field_width)
290 lcfg.msg_type_field_width = 24;
291 log2logger(*log_cfg.file_logger, rep, lcfg);
294 if(actions & SC_STOP) {
297 }
catch(
const spdlog::spdlog_ex& e) {
299#if SYSTEMC_VERSION < 20241015
300 static const int stop_expr = sc_core::SC_START_OF_SIMULATION | SC_RUNNING | SC_PAUSED;
302 static constexpr int stop_expr = sc_core::SC_START_OF_SIMULATION | SC_RUNNING | SC_PAUSED | SC_SUSPENDED;
304 if((sc_get_status() & stop_expr) && !sc_stop_called) {
306 sc_stop_called =
true;
309 if(actions & SC_ABORT) {
312 }
catch(
const spdlog::spdlog_ex& e) {
317 if(actions & SC_THROW) {
320 }
catch(
const spdlog::spdlog_ex& e) {
324 if(sc_time_stamp().value() && !sc_is_running()) {
327 }
catch(
const spdlog::spdlog_ex& e) {
338 old_buf = os.rdbuf(
this);
350auto scc::stream_redirection::xsputn(
const char_type* s, streamsize n) -> streamsize {
351 auto sz = stringbuf::xsputn(s, n);
352 if(s[n - 1] ==
'\n') {
358static const array<sc_severity, 8> severity = {SC_FATAL,
366static const array<sc_verbosity, 8> verbosity = {SC_NONE,
375auto scc::stream_redirection::sync() ->
int {
376 if(level <= log_cfg.level) {
377 auto timestr = time2string(sc_time_stamp());
378 istringstream buf(str());
380 while(getline(buf, line)) {
381 ::sc_report_handler::report(severity[
static_cast<unsigned>(level)],
"SystemC", line.c_str(),
382 verbosity[
static_cast<unsigned>(level)],
"", 0);
389static void configure_logging() {
390 std::lock_guard<mutex> lock(log_cfg.mtx);
392 static bool spdlog_initialized =
false;
393 if(!log_cfg.dont_create_broker)
394 scc::init_cci(
"SCCBroker");
395 log_cfg.broker = cci::cci_get_global_broker(originator);
396 if(log_cfg.install_handler) {
397 if(!log_cfg.instance_based_log_levels || getenv(
"SCC_DISABLE_INSTANCE_BASED_LOGGING"))
398 inst_based_logging() =
false;
399 sc_report_handler::set_verbosity_level(verbosity[
static_cast<unsigned>(log_cfg.level)]);
400 sc_report_handler::set_handler(report_handler);
401 if(!spdlog_initialized) {
402 spdlog::init_thread_pool(1024U,
403 log_cfg.log_file_name.size() ? 2U : 1U);
404 log_cfg.console_logger = log_cfg.log_async ? spdlog::stdout_color_mt<spdlog::async_factory>(
"console_logger")
405 : spdlog::stdout_color_mt(
"console_logger");
406 auto logger_fmt = log_cfg.print_severity ?
"[%L] %v" :
"%v";
407 if(log_cfg.colored_output) {
408 std::ostringstream os;
409 os <<
"%^" << logger_fmt <<
"%$";
410 log_cfg.console_logger->set_pattern(os.str());
412 log_cfg.console_logger->set_pattern(
"[%L] %v");
413 log_cfg.console_logger->flush_on(spdlog::level::err);
414 log_cfg.console_logger->set_level(spdlog::level::level_enum::trace);
415 if(log_cfg.log_file_name.size()) {
418 ofs.open(log_cfg.log_file_name, ios::out | ios::trunc);
420 log_cfg.file_logger = log_cfg.log_async
421 ? spdlog::basic_logger_mt<spdlog::async_factory>(
"file_logger", log_cfg.log_file_name)
422 : spdlog::basic_logger_mt(
"file_logger", log_cfg.log_file_name);
423 if(log_cfg.print_severity)
424 log_cfg.file_logger->set_pattern(
"[%8l] %v");
426 log_cfg.file_logger->set_pattern(
"%v");
427 log_cfg.file_logger->flush_on(spdlog::level::err);
428 log_cfg.file_logger->set_level(spdlog::level::level_enum::trace);
430 spdlog_initialized =
true;
432 log_cfg.console_logger = spdlog::get(
"console_logger");
433 if(log_cfg.log_file_name.size())
434 log_cfg.file_logger = spdlog::get(
"file_logger");
436 if(log_cfg.log_filter_regex.size()) {
438 regcomp(&log_cfg.start_state, log_cfg.log_filter_regex.c_str(), REG_EXTENDED);
440 log_cfg.reg_ex = regex(log_cfg.log_filter_regex, regex::extended | regex::icase);
443 logging::LoggerCallbacks::set_output_cb([](
logging::log_level lvl, std::string
const& msg_type, std::string
const& msg) {
445 case logging::log_level::FATAL:
446 ::scc ::ScLogger<::sc_core ::SC_FATAL>(
"", 0, sc_core ::SC_MEDIUM)
447 .type(msg_type.size() ? msg_type : std::string(
"C++"))
451 case logging::log_level::ERR:
452 ::scc ::ScLogger<::sc_core ::SC_ERROR>(
"", 0, sc_core ::SC_MEDIUM)
453 .type(msg_type.size() ? msg_type : std::string(
"C++"))
457 case logging::log_level::WARN:
458 if(::scc ::get_log_verbosity(msg_type) >= sc_core ::SC_LOW)
459 ::scc ::ScLogger<::sc_core ::SC_WARNING>(
"", 0, sc_core ::SC_MEDIUM)
460 .type(msg_type.size() ? msg_type : std::string(
"C++"))
464 case logging::log_level::INFO:
465 if(::scc ::get_log_verbosity(msg_type) >= sc_core ::SC_MEDIUM)
466 ::scc ::ScLogger<::sc_core ::SC_INFO>(
"", 0, sc_core ::SC_MEDIUM)
467 .type(msg_type.size() ? msg_type : std::string(
"C++"))
471 case logging::log_level::DEBUG:
472 if(::scc ::get_log_verbosity(msg_type) >= sc_core ::SC_HIGH)
473 ::scc ::ScLogger<::sc_core ::SC_INFO>(
"", 0, sc_core ::SC_HIGH)
474 .type(msg_type.size() ? msg_type : std::string(
"C++"))
478 case logging::log_level::TRACE:
479 if(::scc ::get_log_verbosity(msg_type) >= sc_core ::SC_FULL)
480 ::scc ::ScLogger<::sc_core ::SC_INFO>(
"", 0, sc_core ::SC_FULL).type(msg_type).get() << msg;
482 case logging::log_level::TRACEALL:
483 if(::scc ::get_log_verbosity(msg_type) >= sc_core ::SC_DEBUG)
484 ::scc ::ScLogger<::sc_core ::SC_INFO>(
"", 0, sc_core ::SC_DEBUG)
485 .type(msg_type.size() ? msg_type : std::string(
"C++"))
496void scc::reinit_logging() { reinit_logging(log_cfg.level); }
498void scc::reinit_logging(
scc::log level) {
499 if(log_cfg.install_handler)
500 sc_report_handler::set_handler(report_handler);
501 log_cfg.level = level;
503 if(!log_cfg.instance_based_log_levels || getenv(
"SCC_DISABLE_INSTANCE_BASED_LOGGING"))
504 inst_based_logging() =
false;
505 log_cfg.initialized =
true;
511 log_cfg.msg_type_field_width = type_field_width;
512 log_cfg.print_sys_time = print_time;
513 log_cfg.level = level;
515 log_cfg.initialized =
true;
519 log_cfg = log_config;
521 log_cfg.initialized =
true;
526 log_cfg.level = level;
527 sc_report_handler::set_verbosity_level(verbosity[
static_cast<unsigned>(level)]);
528 log_cfg.console_logger->set_level(
529 static_cast<spdlog::level::level_enum
>(SPDLOG_LEVEL_OFF - min<int>(SPDLOG_LEVEL_OFF,
static_cast<int>(log_cfg.level))));
530 log_cfg.initialized =
true;
543 this->msg_type_field_width = width;
548 this->print_sys_time = enable;
553 this->print_sim_time = enable;
558 this->print_delta = enable;
563 this->print_severity = enable;
568 this->log_file_name = name;
573 this->log_file_name = name;
578 this->colored_output = enable;
583 this->log_filter_regex = expr;
588 this->log_filter_regex = expr;
598 this->dont_create_broker = v;
603 this->report_only_first_error = v;
607 this->instance_based_log_levels = v;
611 this->install_handler = v;
616auto get_log_verbosity_from_broker(
string current_name,
char const* str, cci::cci_broker_handle
const& broker, sc_core::sc_verbosity verb)
617 -> sc_core::sc_verbosity {
618 std::lock_guard<std::mutex> lk(mtx);
620 string param_name = (current_name.empty()) ? SCC_LOG_LEVEL_PARAM_NAME : current_name +
"." SCC_LOG_LEVEL_PARAM_NAME;
621 auto h = broker.get_param_handle(param_name);
623 sc_core::sc_verbosity ret = verbosity.at(std::min<unsigned>(h.get_cci_value().get_int(), verbosity.size() - 1));
624 lut.insert(str, ret);
627 auto val = broker.get_preset_cci_value(param_name);
629 sc_core::sc_verbosity ret = verbosity.at(std::min<unsigned>(val.get_int(), verbosity.size() - 1));
630 lut.insert(str, ret);
633 if(current_name.empty()) {
634 lut.insert(str, verb);
637 auto pos = current_name.rfind(
".");
638 if(pos == std::string::npos) {
641 current_name = current_name.substr(0, pos);
651 auto global_verb = verbosity[
static_cast<unsigned>(log_cfg.level)];
652 if(inst_based_logging()) {
653 auto res = lut.get(str);
655 return std::get<1>(res);
656 auto* curr_object = sc_core::sc_get_current_object();
657 if(strchr(str,
'.') ==
nullptr || curr_object) {
658 string current_name = std::string(str);
660 return get_log_verbosity_from_broker(current_name, str, log_cfg.broker.value(), global_verb);
662 return get_log_verbosity_from_broker(
663 current_name, str, curr_object ? cci::cci_get_broker() : cci::cci_get_global_broker(originator), global_verb);
~stream_redirection()
destructor restoring the output stream buffer
void reset()
reset the stream redirection and restore output buffer of the stream
stream_redirection(std::ostream &os, log level)
constructor redirecting the given stream to a SystemC log message of given llog level
log_level
enum defining the log levels
void set_logging_level(log level)
sets the SystemC logging level
void init_logging(log level=log::WARNING, unsigned type_field_width=24, bool print_time=false)
initializes the SystemC logging system with a particular logging level
bool is_logging_initialized()
get the state of the SCC logging system
void set_cycle_base(sc_core::sc_time period)
sets the cycle base for cycle based logging
log get_logging_level()
get the SystemC logging level
sc_core::sc_verbosity get_log_verbosity()
get the global verbosity level
log
enum defining the log levels
std::mutex verbosity_mtx
a mutex needed to syncronize verbosity manipulations
std::string padded(std::string str, size_t width, bool show_ellipsis=true)
pad a string to a given length by either cutting of the overflow or inserting an ellipsis
the configuration class for the logging setup
LogConfig & printSeverity(bool=true)
LogConfig & printSysTime(bool=true)
LogConfig & reportOnlyFirstError(bool=true)
LogConfig & coloredOutput(bool=true)
LogConfig & logFileName(std::string &&)
LogConfig & dontCreateBroker(bool=true)
LogConfig & logLevel(log)
LogConfig & msgTypeFieldWidth(unsigned)
LogConfig & printSimTime(bool=true)
LogConfig & logAsync(bool=true)
LogConfig & printDelta(bool=true)
LogConfig & instanceBasedLogLevels(bool=true)
LogConfig & installHandler(bool=true)
LogConfig & logFilterRegex(std::string &&)