Skip to content

Commit

Permalink
log: Display internal source location for LOG(DEBUG) logs
Browse files Browse the repository at this point in the history
Helps with debugging. A slightly more powerful printf.
  • Loading branch information
danobi committed Mar 19, 2024
1 parent e8fe628 commit 19239ad
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
22 changes: 16 additions & 6 deletions src/log.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -184,15 +184,26 @@ LogStream::~LogStream()
// occur. So, we cannot simply DISABLE_LOG(ERROR). Instead, here, we don't
// output error messages to stderr.
if (sink_.is_enabled(type_) &&
(type_ != LogType::ERROR || (&out_ != &std::cout && &out_ != &std::cerr)))
(type_ != LogType::ERROR ||
(&out_ != &std::cout && &out_ != &std::cerr))) {
#else
if (sink_.is_enabled(type_))
if (sink_.is_enabled(type_)) {
#endif
{
sink_.take_input(type_, loc_, out_, buf_.str());
auto msg = buf_.str();
if (type_ == LogType::DEBUG)
msg = internal_location() + msg;

sink_.take_input(type_, loc_, out_, std::move(msg));
}
}

std::string LogStream::internal_location()
{
std::ostringstream ss;
ss << "[" << log_file_ << ":" << log_line_ << "] ";
return ss.str();
}

[[noreturn]] LogStreamFatal::~LogStreamFatal()
{
sink_.take_input(type_, loc_, out_, buf_.str());
Expand All @@ -201,8 +212,7 @@ LogStream::~LogStream()

[[noreturn]] LogStreamBug::~LogStreamBug()
{
std::string prefix = "[" + log_file_ + ":" + std::to_string(log_line_) + "] ";
sink_.take_input(type_, loc_, out_, prefix + buf_.str());
sink_.take_input(type_, loc_, out_, internal_location() + buf_.str());
abort();
}

Expand Down
2 changes: 2 additions & 0 deletions src/log.h
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ class LogStream {
virtual ~LogStream();

protected:
std::string internal_location();

Log& sink_;
LogType type_;
const std::optional<location> loc_;
Expand Down

0 comments on commit 19239ad

Please sign in to comment.