From 15bf481120a8ad80436f0848afae6b1d0cb1d228 Mon Sep 17 00:00:00 2001 From: Johan Wikman Date: Thu, 16 Aug 2018 13:54:07 +0300 Subject: [PATCH] MXS-2014 Allow the header and footer to be adjusted --- maxutils/maxbase/include/maxbase/logger.hh | 11 ++++++ maxutils/maxbase/src/logger.cc | 39 +++++++++++++++++++--- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/maxutils/maxbase/include/maxbase/logger.hh b/maxutils/maxbase/include/maxbase/logger.hh index 301a8dc0f..4c2e9f5b1 100644 --- a/maxutils/maxbase/include/maxbase/logger.hh +++ b/maxutils/maxbase/include/maxbase/logger.hh @@ -34,6 +34,17 @@ public: { } + /** + * Set the identification, used in log header and footer. + * If not specified, the program name will be used. + * + * @param ident The identifying string. + * + * @attention The identification should be specified before the + * log is initialized. + */ + static void set_ident(const std::string& ident); + /** * Write a message to the log * diff --git a/maxutils/maxbase/src/logger.cc b/maxutils/maxbase/src/logger.cc index cac871516..f71c1a391 100644 --- a/maxutils/maxbase/src/logger.cc +++ b/maxutils/maxbase/src/logger.cc @@ -67,6 +67,25 @@ bool should_log_error() return rval; } +struct this_unit +{ + std::string ident; +} this_unit; + +std::string get_ident() +{ + if (this_unit.ident.empty()) + { +#ifdef __GNUC__ + this_unit.ident = program_invocation_short_name; +#else + this_unit.ident = "The Program"; +#endif + } + + return this_unit.ident; +} + } namespace maxbase @@ -76,6 +95,12 @@ namespace maxbase // Public methods // +// static +void Logger::set_ident(const std::string& ident) +{ + this_unit.ident = ident; +} + std::unique_ptr FileLogger::create(const std::string& filename) { std::unique_ptr logger; @@ -103,7 +128,11 @@ FileLogger::~FileLogger() std::lock_guard guard(m_lock); // As mxb_assert() logs to the log-file, it cannot be used here. assert(m_fd != -1); - close("MariaDB MaxScale is shut down."); + + std::string suffix = get_ident(); + suffix += " is shut down."; + + close(suffix.c_str()); } bool FileLogger::write(const char* msg, int len) @@ -177,14 +206,14 @@ bool FileLogger::write_header() struct tm tm; localtime_r(&t, &tm); - const char PREFIX[] = "MariaDB MaxScale "; // sizeof(PREFIX) includes the NULL. + std::string ident = get_ident(); char time_string[32]; // 26 would be enough, according to "man asctime". asctime_r(&tm, time_string); - size_t size = sizeof(PREFIX) + m_filename.length() + 2 * sizeof(' ') + strlen(time_string); + size_t size = ident.length() + 2 * sizeof(' ') + m_filename.length() + 2 * sizeof(' ') + strlen(time_string); - char header[size + 2]; // For the 2 newlines. - sprintf(header, "\n\n%s%s %s", PREFIX, m_filename.c_str(), time_string); + char header[size + 2 + 1]; // For the 2 newlines and the trailing NULL. + sprintf(header, "\n\n%s %s %s", ident.c_str(), m_filename.c_str(), time_string); char line[sizeof(header) - 1]; memset(line, '-', sizeof(line) - 1);