From 12e8f28907cb7c2661cbc86b8aa7e4f6104a0117 Mon Sep 17 00:00:00 2001 From: Johan Wikman Date: Thu, 16 Aug 2018 13:18:16 +0300 Subject: [PATCH] MXS-2014 Add mxb::Log class for convenience In tests, the log can now be setup as int main() { mxb::Log log; ... } That will initialize the log so that it logs to a file called .log in the current directory and finalize it when the program exits. --- maxutils/maxbase/include/maxbase/log.hh | 74 +++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 maxutils/maxbase/include/maxbase/log.hh diff --git a/maxutils/maxbase/include/maxbase/log.hh b/maxutils/maxbase/include/maxbase/log.hh new file mode 100644 index 000000000..2fbc355a7 --- /dev/null +++ b/maxutils/maxbase/include/maxbase/log.hh @@ -0,0 +1,74 @@ +#pragma once +/* + * Copyright (c) 2016 MariaDB Corporation Ab + * + * Use of this software is governed by the Business Source License included + * in the LICENSE.TXT file and at www.mariadb.com/bsl11. + * + * Change Date: 2022-01-01 + * + * On the date above, in accordance with the Business Source License, use + * of this software will be governed by version 2 or later of the General + * Public License. + */ + +#include +#include +#include + +/** + * @brief Initialize the log + * + * This function initializes the log using + * - the program name as the syslog ident, + * - the current directory as the logdir, and + * - the default log name (program name + ".log"). + * + * @param target The specified target for the logging. + * + * @return True if succeeded, false otherwise. + */ +bool mxb_log_init(mxb_log_target_t target = MXB_LOG_TARGET_FS) +{ + return mxb_log_init(nullptr, ".", nullptr, target, nullptr); +} + +namespace maxbase +{ + +/** + * @class Log + * + * A simple utility RAII class where the constructor initializes the log and + * the destructor finalizes it. + */ +class Log +{ + Log(const Log&) = delete; + Log& operator=(const Log&) = delete; + +public: + Log(const char* ident, + const char* logdir, + const char* filename, + mxb_log_target_t target, + mxb_log_context_provider_t context_provider) + { + if (!mxb_log_init(ident, logdir, filename, target, context_provider)) + { + throw std::runtime_error("Failed to initialize the log."); + } + } + + Log(mxb_log_target_t target = MXB_LOG_TARGET_FS) + : Log(nullptr, ".", nullptr, target, nullptr) + { + } + + ~Log() + { + mxb_log_finish(); + } +}; + +}