Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding setLogLevel feature #264

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 32 additions & 5 deletions media-proxy/include/mesh/logger.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ enum class Level {
fatal
};

extern Level currentLogLevel;

class Formatter {
public:
virtual void formatMessage(std::ostringstream& ostream,
Expand Down Expand Up @@ -68,14 +70,14 @@ extern std::unique_ptr<Formatter> formatter;
class Logger {
public:
Logger(Level level, const char *format, va_list args);
Logger(Logger&& other) noexcept : ostream(std::move(other.ostream)) {}
Logger(Logger&& other) noexcept : level(other.level), ostream(std::move(other.ostream)) {}
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
~Logger();

template<typename T>
Logger& operator()(const char *key, const T& value) {
if (formatter)
if (formatter && level >= currentLogLevel)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You still print the log message here no matter which log level is set, right? You only avoid formatter methods to be called if the level is disabled.

formatter->formatKeyValueBefore(ostream, key);

using DecayedT = std::decay_t<T>;
Expand All @@ -88,12 +90,13 @@ class Logger {
else
ostream << value;

if (formatter)
if (formatter && level >= currentLogLevel)
formatter->formatKeyValueAfter(ostream, key);
return *this;
}

private:
Level level;
std::ostringstream ostream;
};

Expand Down Expand Up @@ -130,6 +133,31 @@ class Logger {
* {"time":"2024-11-15T00:27:30.300Z","level":"error","msg":"High load","percent":99.8,"num_clients":9801}
* {"time":"2024-11-15T00:27:30.300Z","level":"debug","msg":"Counter incremented","cnt":355}
* {"time":"2024-11-15T00:27:30.300Z","level":"fatal","msg":"Emergency exit","err_code":312645}
* Example C: Setting the log level dynamically
* ============================================
* mesh::log::setLogLevel(mesh::log::Level::warn); // Set minimum log level to WARN
*
* log::info("This message will not be displayed")("id", "123456");
* log::warn("Low memory warning")("available_mb", 512);
* log::error("Critical error occurred")("error_code", 5001);
* log::debug("Debugging details")("step", "init");
*
* Output:
* Nov 15 00:26:07.672 [WARN] Low memory warning available_mb=512
* Nov 15 00:26:07.672 [ERRO] Critical error occurred error_code=5001
* Nov 15 00:26:07.672 [DEBU] Debugging details step=init
* Example D: Adjusting log levels during runtime
* ==============================================
* mesh::log::setLogLevel(mesh::log::Level::info); // Enable all log messages
* log::info("Re-enabled info logging")("reason", "debugging mode");
*
* Output:
* Nov 15 00:26:07.672 [INFO] Re-enabled info logging reason="debugging mode"
*
* Features:
* - Use `mesh::log::setLogLevel(mesh::log::Level)` to dynamically adjust log filtering.
* - Supported log levels: `info`, `warn`, `error`, `debug`, `fatal`.
* - Messages below the set log level will be ignored.
*/
Logger info(const char* format, ...);
Logger warn(const char* format, ...);
Expand All @@ -138,8 +166,7 @@ Logger debug(const char* format, ...);
Logger fatal(const char* format, ...);

void setFormatter(std::unique_ptr<Formatter> new_formatter);

// TODO: Add an option to set the log level.
void setLogLevel(Level level);

} // namespace mesh::log

Expand Down
19 changes: 12 additions & 7 deletions media-proxy/src/mesh/logger.cc
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace mesh::log {

Level currentLogLevel = Level::info;

void StandardFormatter::formatMessage(std::ostringstream& ostream, Level level,
const char *format, va_list args)
{
Expand Down Expand Up @@ -113,21 +115,24 @@ void setFormatter(std::unique_ptr<Formatter> new_formatter)
formatter = std::move(new_formatter);
}

void setLogLevel(Level level) {
currentLogLevel = level;
}
Comment on lines +118 to +120
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function is not thread-safe. Since there is no meaning in changing the log level at runtime, I suggest to leave this function as it is but say in the comment block that this is to be called only once the logger is created in the app.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually there was a meaning for me - for different tests I wanted to have control over what is visible where, I'll make it thread safe.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you make it thread safe, you'll make currentLogLevel thread safe. It will add latency to printing messages. Please don't.


Logger::Logger(Level level, const char *format, va_list args)
{
if (formatter) {
if (level >= currentLogLevel && formatter) {
formatter->formatBefore(ostream);
formatter->formatMessage(ostream, level, format, args);
}
}

Logger::~Logger()
{
if (formatter)
formatter->formatAfter(ostream);

if (!ostream.str().empty())
Logger::~Logger() {
if (!ostream.str().empty() && level >= currentLogLevel) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (!ostream.str().empty() && level >= currentLogLevel) {
if (level >= currentLogLevel && !ostream.str().empty()) {

if (formatter)
formatter->formatAfter(ostream);
std::cout << ostream.str() << std::endl;
}
}

Logger info(const char* format, ...)
Expand Down