OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[Logger] Add log callback setup (#31165)
Tomasz Jankowski2595451955c1
diff --git a/src/common/util/include/openvino/util/log.hpp b/src/common/util/include/openvino/util/log.hppindex 4f4606ee61d..eb4e5237440 100644--- a/src/common/util/include/openvino/util/log.hpp+++ b/src/common/util/include/openvino/util/log.hpp@@ -17,8 +17,7 @@#include "openvino/util/env_util.hpp"-namespace ov {-namespace util {+namespace ov::util {enum class LOG_TYPE {_LOG_TYPE_ERROR,@@ -30,7 +29,7 @@ enum class LOG_TYPE {class LogHelper {public:- LogHelper(LOG_TYPE, const char* file, int line, std::function<void(const std::string&)> m_handler_func);+ LogHelper(LOG_TYPE, const char* file, int line);~LogHelper();std::ostream& stream() {@@ -38,29 +37,9 @@ public:}private:- std::function<void(const std::string&)> m_handler_func;std::stringstream m_stream;};-class Logger {- friend class LogHelper;--public:- static void set_log_path(const std::string& path);- static void start();- static void stop();--private:- static void log_item(const std::string& s);- static void process_event(const std::string& s);- static void thread_entry(void* param);- static std::string m_log_path;- static std::deque<std::string> m_queue;-};--void default_logger_handler_func(const std::string& s);-void default_logger_handler_func_length(const std::string& s);-#ifdef ENABLE_OPENVINO_DEBUG/* Template function _write_all_to_stream has duplicates* It's defined in:@@ -77,12 +56,8 @@ static inline std::ostream& _write_all_to_stream(std::ostream& os, const T& arg,return ov::util::_write_all_to_stream(os << arg, std::forward<TS>(args)...);}-# define OPENVINO_LOG_STREAM(OPENVINO_HELPER_LOG_TYPE) \- ::ov::util::LogHelper(::ov::util::LOG_TYPE::OPENVINO_HELPER_LOG_TYPE, \- __FILE__, \- __LINE__, \- ::ov::util::default_logger_handler_func) \- .stream()+# define OPENVINO_LOG_STREAM(OPENVINO_HELPER_LOG_TYPE) \+ ::ov::util::LogHelper(::ov::util::LOG_TYPE::OPENVINO_HELPER_LOG_TYPE, __FILE__, __LINE__).stream()# define OPENVINO_ERR(...) \do { \@@ -156,5 +131,4 @@ static inline bool is_terminal_output() {} while (0)#endif-} // namespace util-} // namespace ov+} // namespace ov::utildiff --git a/src/common/util/src/log.cpp b/src/common/util/src/log.cppindex 8cf2cdf9e29..8f58e6b0edc 100644--- a/src/common/util/src/log.cpp+++ b/src/common/util/src/log.cpp@@ -12,21 +12,15 @@#include "openvino/util/file_util.hpp"-void ov::util::default_logger_handler_func(const std::string& s) {- std::cout << s << std::endl;-}+namespace ov::util {-ov::util::LogHelper::LogHelper(LOG_TYPE type,- const char* file,- int line,- std::function<void(const std::string&)> handler_func)- : m_handler_func(std::move(handler_func)) {+LogHelper::LogHelper(LOG_TYPE type, const char* file, int line) {switch (type) {case LOG_TYPE::_LOG_TYPE_ERROR:- m_stream << "[ERR] ";+ m_stream << "[ERROR] ";break;case LOG_TYPE::_LOG_TYPE_WARNING:- m_stream << "[WARN] ";+ m_stream << "[WARNING] ";break;case LOG_TYPE::_LOG_TYPE_INFO:m_stream << "[INFO] ";@@ -52,16 +46,14 @@ ov::util::LogHelper::LogHelper(LOG_TYPE type,}m_stream << util::trim_file_name(file);- m_stream << " " << line;+ m_stream << ":" << line;m_stream << "\t";}}-ov::util::LogHelper::~LogHelper() {-#ifdef ENABLE_OPENVINO_DEBUG- if (m_handler_func) {- m_handler_func(m_stream.str());- }- // Logger::log_item(m_stream.str());-#endif+void log_message(std::string_view);++LogHelper::~LogHelper() {+ log_message(m_stream.str());}+} // namespace ov::utildiff --git a/src/core/dev_api/openvino/core/log_util.hpp b/src/core/dev_api/openvino/core/log_util.hppindex 8982bfb1ab7..7485e7de3a2 100644--- a/src/core/dev_api/openvino/core/log_util.hpp+++ b/src/core/dev_api/openvino/core/log_util.hpp@@ -6,14 +6,22 @@#include <memory>#include <string>+#include <string_view>#include "openvino/core/core_visibility.hpp"#include "openvino/core/node.hpp"-#ifdef ENABLE_OPENVINO_DEBUG+namespace ov::util {++using LogCallback = std::function<void(std::string_view)>;-namespace ov {-namespace util {+/** @brief Logs the message using current log callback object.+ * @param [in] message text to be logged.+ */+OPENVINO_API+void log_message(std::string_view message);++#ifdef ENABLE_OPENVINO_DEBUGclass OPENVINO_API LevelString {private:@@ -556,10 +564,7 @@ OPENVINO_API std::string node_with_arguments(const ov::Node& node);(status ? " ALL ARGUMENTS MATCHED" : " ARGUMENTS DIDN'T MATCH")); \} while (0);-} // namespace util-} // namespace ov--#else+#else // ENABLE_OPENVINO_DEBUG# define OPENVINO_LOG_GENPATTERN1(...) \do { \@@ -699,4 +704,5 @@ OPENVINO_API std::string node_with_arguments(const ov::Node& node);do { \} while (0)-#endif\ No newline at end of file+#endif // ENABLE_OPENVINO_DEBUG+} // namespace ov::utildiff --git a/src/core/include/openvino/core/log.hpp b/src/core/include/openvino/core/log.hppnew file mode 100644index 00000000000..2f2c6eee382--- /dev/null+++ b/src/core/include/openvino/core/log.hpp@@ -0,0 +1,27 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <functional>+#include <string_view>++#include "openvino/core/core_visibility.hpp"++namespace ov::util {++/**+ * @brief Resets log messages handling callback to its default (`std::cout').+ */+OPENVINO_API+void reset_log_callback();++/**+ * @brief Sets user log messages handling callback.+ * @param [in] callback A reference to callable object which is called on single message logging.+ * Empty object is fine - nothing is logged.+ */+OPENVINO_API+void set_log_callback(const std::function<void(std::string_view)>& callback);+} // namespace ov::utildiff --git a/src/core/src/log.cpp b/src/core/src/log.cppnew file mode 100644index 00000000000..d282e9f15dd--- /dev/null+++ b/src/core/src/log.cpp@@ -0,0 +1,38 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/core/log.hpp"++#include "openvino/core/log_util.hpp"++namespace ov::util {+namespace {+const LogCallback default_callback{[](std::string_view s) {+ std::cout << s << std::endl;+}};++const LogCallback silent_callback{[](std::string_view s) {}};++const LogCallback* current_callback = &default_callback;+} // namespace++OPENVINO_API+void reset_log_callback() {+ current_callback = &default_callback;+}++OPENVINO_API+void set_log_callback(const std::function<void(std::string_view)>& callback) {+ if (!callback) {+ current_callback = &silent_callback;+ } else {+ current_callback = &callback;+ }+}++OPENVINO_API+void log_message(std::string_view message) {+ (*current_callback)(message);+}+} // namespace ov::utildiff --git a/src/core/tests/logger.cpp b/src/core/tests/logger.cppnew file mode 100644index 00000000000..075977b48b2--- /dev/null+++ b/src/core/tests/logger.cpp@@ -0,0 +1,140 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include <iostream>+#include <regex>+#include <sstream>++#include "openvino/core/log.hpp"+#include "openvino/core/log_util.hpp"+#include "openvino/util/log.hpp"++namespace ov::tests {++using namespace ov::util;++// Capturing std::cout streambuffer doesn't work in a CI job on Windows, so disabled. Tested locally on Ubuntu.+static constexpr bool enable_logging_to_std_cout_test = false;++using LogEntries = std::tuple<LOG_TYPE, const char*, int, const char*>;++class TestLogHelper : public testing::TestWithParam<LogEntries> {+ std::ostream* const actual_out_stream = &std::cout;+ std::streambuf* const actual_out_buf = actual_out_stream->rdbuf();++ // LogEntries+ LOG_TYPE m_log_type;+ const char* m_log_path;+ int m_log_line;+ const char* m_log_message;++protected:+ void SetUp() override {+ reset_log_callback();+ if (enable_logging_to_std_cout_test) {+ actual_out_stream->flush();+ actual_out_stream->rdbuf(m_mock_out_stream.rdbuf());+ }++ std::tie(m_log_type, m_log_path, m_log_line, m_log_message) = GetParam();+ }++ void TearDown() override {+ if (enable_logging_to_std_cout_test) {+ actual_out_stream->rdbuf(actual_out_buf);+ }+ reset_log_callback();+ }++ auto log_test_params() {+ LogHelper{m_log_type, m_log_path, m_log_line}.stream() << m_log_message;+ }++ auto get_log_regex() const {+ static auto log_prefix_pattern =+ std::map<LOG_TYPE, const std::string>{{LOG_TYPE::_LOG_TYPE_ERROR, R"(\[ERROR\])"},+ {LOG_TYPE::_LOG_TYPE_WARNING, R"(\[WARNING\])"},+ {LOG_TYPE::_LOG_TYPE_INFO, R"(\[INFO\])"},+ {LOG_TYPE::_LOG_TYPE_DEBUG, R"(\[DEBUG\])"}};+ std::stringstream log_regex;+ if (LOG_TYPE::_LOG_TYPE_DEBUG_EMPTY != m_log_type) {+ log_regex << log_prefix_pattern[m_log_type] << ".*" << m_log_path << ".*" << m_log_line << ".*";+ }+ log_regex << m_log_message;+ return std::regex{log_regex.str()};+ }++ auto are_params_logged_to(const std::string& buf) {+ return std::regex_search(buf, get_log_regex());+ }++ std::stringstream m_mock_out_stream;++ std::string m_callback_message;+ const LogCallback m_log_callback{[this](std::string_view msg) {+ m_callback_message = msg;+ }};+};++TEST_P(TestLogHelper, set_callback) {+ if (enable_logging_to_std_cout_test) {+ log_test_params();+ EXPECT_TRUE(are_params_logged_to(m_mock_out_stream.str()))+ << "Mock cout got: '" << m_mock_out_stream.str() << "'\n";+ m_mock_out_stream.str("");+ m_mock_out_stream.clear();+ }+ set_log_callback(m_log_callback);+ log_test_params();+ if (enable_logging_to_std_cout_test) {+ EXPECT_TRUE(m_mock_out_stream.str().empty()) << "Expected no cout. Got: '" << m_mock_out_stream.str() << "'\n";+ }+ EXPECT_TRUE(are_params_logged_to(m_callback_message)) << "Callback got: '" << m_callback_message << "'\n";+}++TEST_P(TestLogHelper, toggle_callbacks) {+ set_log_callback(m_log_callback);+ log_test_params();+ EXPECT_TRUE(are_params_logged_to(m_callback_message)) << "1st callback got: '" << m_callback_message << "'\n";+ m_callback_message.clear();+ std::string aux_callback_msg;+ const LogCallback aux_callback = [&aux_callback_msg](std::string_view msg) {+ aux_callback_msg = msg;+ };+ set_log_callback(aux_callback);+ log_test_params();+ EXPECT_TRUE(are_params_logged_to(aux_callback_msg)) << "2st callback got: '" << aux_callback_msg << "'\n";+ EXPECT_TRUE(m_callback_message.empty()) << "Expected no 1st callback. Got: '" << m_callback_message << "'\n";+}++TEST_P(TestLogHelper, reset) {+ set_log_callback(m_log_callback);+ reset_log_callback();+ log_test_params();++ if (enable_logging_to_std_cout_test) {+ EXPECT_TRUE(are_params_logged_to(m_mock_out_stream.str()))+ << "Mock cout got: '" << m_mock_out_stream.str() << "'\n";+ }+ EXPECT_TRUE(m_callback_message.empty()) << "Expected no callback. Got: '" << m_callback_message << "'\n";+}++TEST_P(TestLogHelper, no_log) {+ set_log_callback(m_log_callback);+ const auto empty_callback = LogCallback{};+ set_log_callback(empty_callback);+ ASSERT_NO_THROW(log_test_params());+ EXPECT_TRUE(m_callback_message.empty()) << "Expected no callback. Got: '" << m_callback_message << "'\n";+}++INSTANTIATE_TEST_SUITE_P(Log_callback,+ TestLogHelper,+ ::testing::Values(LogEntries{LOG_TYPE::_LOG_TYPE_ERROR, "path_1", 1, "text 1"},+ LogEntries{LOG_TYPE::_LOG_TYPE_WARNING, "path_2", 2, "text 2"},+ LogEntries{LOG_TYPE::_LOG_TYPE_INFO, "path_3", 3, "text 3"},+ LogEntries{LOG_TYPE::_LOG_TYPE_DEBUG, "path_4", 4, "text 4"},+ LogEntries{LOG_TYPE::_LOG_TYPE_DEBUG_EMPTY, "path_5", 5, "text 5"}));+} // namespace ov::testsdiff --git a/src/frontends/paddle/src/input_model.cpp b/src/frontends/paddle/src/input_model.cppindex 9b284c89d17..33faec4e4f9 100644--- a/src/frontends/paddle/src/input_model.cpp+++ b/src/frontends/paddle/src/input_model.cpp@@ -13,6 +13,7 @@#include "decoder_proto.hpp"#include "framework.pb.h"#include "input_model.hpp"+#include "openvino/core/log_util.hpp"#include "openvino/frontend/paddle/node_context.hpp"#include "openvino/opsets/opset7.hpp"#include "openvino/util/common_util.hpp"@@ -440,8 +441,8 @@ void InputModel::InputModelImpl::create_temp_consts() {const auto& tensor = var_desc.type().tensor_array().tensor();const auto& type = get_ov_type(tensor.data_type());- std::cout << "WARNING: The PaddlePaddle model has \"TENSOR_ARRAY\" variables, which is supported "- << " under limited situations.\n";+ util::log_message("WARNING: The PaddlePaddle model has \"TENSOR_ARRAY\" variables, which is supported "+ "under limited situations.");PartialShape tensor_ps(std::vector<Dimension>(tensor.dims().cbegin(), tensor.dims().cend()));tensor_ps.insert(tensor_ps.begin(), 1); // unsqueezediff --git a/src/inference/dev_api/openvino/runtime/plugin_config.hpp b/src/inference/dev_api/openvino/runtime/plugin_config.hppindex 109165b1cd0..80e1daa78c3 100644--- a/src/inference/dev_api/openvino/runtime/plugin_config.hpp+++ b/src/inference/dev_api/openvino/runtime/plugin_config.hpp@@ -10,6 +10,7 @@#include "openvino/core/attribute_visitor.hpp"#include "openvino/core/except.hpp"+#include "openvino/core/log_util.hpp"#include "openvino/runtime/iremote_context.hpp"#include "openvino/runtime/properties.hpp"@@ -189,8 +190,8 @@ protected:: m_option(option) {auto val = PluginConfig::read_env(name, prefix, &option);if (!val.empty()) {- std::cout << "Non default global config value for " << name << " = " << val.template as<std::string>()- << std::endl;+ util::log_message("Non default global config value for " + name + " = " ++ val.template as<std::string>());option.set_any(val);}}diff --git a/src/inference/src/dev/plugin_config.cpp b/src/inference/src/dev/plugin_config.cppindex ac8fc79da30..e871efd1eb9 100644--- a/src/inference/src/dev/plugin_config.cpp+++ b/src/inference/src/dev/plugin_config.cpp@@ -140,7 +140,7 @@ void PluginConfig::apply_env_options() {ov::AnyMap env_properties = read_env();cleanup_unsupported(env_properties);for (auto& [name, val] : env_properties) {- std::cout << "Non default env value for " << name << " = " << val.as<std::string>() << std::endl;+ util::log_message("Non default env value for " + name + " = " + val.as<std::string>());}set_property(env_properties);}@@ -150,7 +150,7 @@ void PluginConfig::apply_config_options(std::string_view device_name, std::filesov::AnyMap config_properties = read_config_file(config_path, device_name);cleanup_unsupported(config_properties);for (auto& [name, val] : config_properties) {- std::cout << "Non default config value for " << name << " = " << val.as<std::string>() << std::endl;+ util::log_message("Non default config value for " + name + " = " + val.as<std::string>());}set_property(config_properties);}diff --git a/src/plugins/auto/src/utils/log.hpp b/src/plugins/auto/src/utils/log.hppindex 41b41deec64..349fb6eb57e 100644--- a/src/plugins/auto/src/utils/log.hpp+++ b/src/plugins/auto/src/utils/log.hpp@@ -18,6 +18,7 @@#include "singleton.hpp"#include "time_utils.hpp"#include "openvino/runtime/properties.hpp"+#include "openvino/core/log_util.hpp"#ifdef MULTIUNITTEST#define MOCKTESTMACRO virtual@@ -127,7 +128,7 @@ inline void Log::set_log_level(ov::log::Level loglevel_) {}inline void Log::print(std::stringstream& stream) {- std::cout << stream.str() << std::endl << std::flush;+ util::log_message(stream.str());}inline void Log::checkFormat(const char* fmt) {@@ -231,4 +232,4 @@ inline std::string Log::colorEnd(ov::log::Level loglevel) {return {};}} // namespace auto_plugin-} // namespace ov\ No newline at end of file+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/logging.hpp b/src/plugins/intel_npu/src/plugin/npuw/logging.hppindex e2c37b1b787..c235876463e 100644--- a/src/plugins/intel_npu/src/plugin/npuw/logging.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/logging.hpp@@ -6,6 +6,7 @@#include <fstream>+#include "openvino/core/log_util.hpp"#include "openvino/openvino.hpp"#include "openvino/runtime/itensor.hpp"#include "openvino/runtime/so_ptr.hpp"@@ -37,14 +38,16 @@ void dump_failure(const std::shared_ptr<ov::Model>& model, const std::string& de} // namespace npuw} // namespace ov-#define LOG_IMPL(str, level, levelstr) \+#define LOG_IMPL(msg, level, levelstr) \do { \if (ov::npuw::get_log_level() >= ov::npuw::LogLevel::level) { \- std::cout << "[ NPUW:" levelstr " ] "; \+ std::stringstream log_stream; \+ log_stream << "[ NPUW:" levelstr " ] "; \const int this_level = ov::npuw::__logging_indent__::__level__(); \for (int i = 0; i < this_level; i++) \- std::cout << " "; \- std::cout << str << std::endl; \+ log_stream << " "; \+ log_stream << msg; \+ ov::util::log_message(log_stream.str()); \} \} while (0)diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/logger/logger.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/logger/logger.hppindex cb0604b8dfc..74a797bc2a3 100644--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/logger/logger.hpp+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/logger/logger.hpp@@ -56,9 +56,6 @@ public:bool isActive(ov::log::Level msgLevel) const;- static std::ostream& getBaseStream();- static std::ostream& getLevelStream(ov::log::Level msgLevel);-template <typename... Args>void error(const char* format, Args&&... args) const {addEntryPacked(ov::log::Level::ERR, format, std::forward<Args>(args)...);diff --git a/src/plugins/intel_npu/src/utils/src/logger/logger.cpp b/src/plugins/intel_npu/src/utils/src/logger/logger.cppindex b0dd9f0f012..197a011bc75 100644--- a/src/plugins/intel_npu/src/utils/src/logger/logger.cpp+++ b/src/plugins/intel_npu/src/utils/src/logger/logger.cpp@@ -12,6 +12,8 @@#include <regex>#include <sstream>+#include "openvino/core/log_util.hpp"+#define DEFAULT_COLOR "\033[0m"#define RED "\033[31m"#define GREEN "\033[32m"@@ -80,45 +82,28 @@ bool Logger::isActive(ov::log::Level msgLevel) const {return static_cast<int32_t>(msgLevel) <= static_cast<int32_t>(_logLevel);}-std::ostream& Logger::getBaseStream() {- return std::cout;-}-namespace {-std::ostream& getColor(ov::log::Level msgLevel) {- std::ostream& stream = std::cout;-+const char* getColor(ov::log::Level msgLevel) {switch (msgLevel) {case ov::log::Level::ERR:- stream << RED;- break;+ return RED;case ov::log::Level::WARNING:- stream << YELLOW;- break;+ return YELLOW;case ov::log::Level::INFO:- stream << CYAN;- break;+ return CYAN;case ov::log::Level::DEBUG:- stream << GREEN;- break;+ return GREEN;case ov::log::Level::TRACE:- stream << BLUE;- break;+ return BLUE;default:- stream << DEFAULT_COLOR;+ return DEFAULT_COLOR;}- return stream;}} // namespace-std::ostream& Logger::getLevelStream(ov::log::Level msgLevel) {- return getColor(msgLevel);-}-void Logger::addEntryPackedActive(ov::log::Level msgLevel, std::string_view msg) const {- std::stringstream tempStream;char timeStr[] = "undefined_time";time_t now = time(nullptr);struct tm* loctime = localtime(&now);@@ -128,24 +113,18 @@ void Logger::addEntryPackedActive(ov::log::Level msgLevel, std::string_view msg)using namespace std::chrono;uint32_t ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count() % 1000;- auto& stream = getLevelStream(msgLevel);try {- tempStream << "[" << logLevelPrintout[static_cast<int32_t>(msgLevel) + 1] << "] " << timeStr << "." << ms- << " [" << _name << "] ";-- tempStream << msg;-+ std::stringstream logStream;+ logStream << getColor(msgLevel) << "[" << logLevelPrintout[static_cast<int32_t>(msgLevel) + 1] << "] "+ << timeStr << "." << ms << " [" << _name << "] " << msg << DEFAULT_COLOR;static std::mutex logMtx;std::lock_guard<std::mutex> logMtxLock(logMtx);- stream << tempStream.str() << DEFAULT_COLOR;- stream << std::endl;- stream.flush();+ ov::util::log_message(logStream.str());} catch (const std::exception& e) {std::cerr << "Exception caught in Logger::addEntryPackedActive - " << e.what() << std::endl;} catch (...) {std::cerr << "Unknown/internal exception happened in Logger::addEntryPackedActive" << std::endl;}- stream.flush();}} // namespace intel_npu