Mantid
Loading...
Searching...
No Matches
PythonLoggingChannel.cpp
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4// NScD Oak Ridge National Laboratory, European Spallation Source,
5// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6// SPDX - License - Identifier: GPL - 3.0 +
7
8// local includes
10
11// 3rd-party includes
13#include <Poco/Message.h>
14#include <boost/python/import.hpp>
15
16namespace Poco {
17
18namespace {
19// See https://docs.python.org/3/library/logging.html#logging-levels
20constexpr int PY_CRITICAL = 50;
21constexpr int PY_ERROR = 40;
22constexpr int PY_WARNING = 30;
23constexpr int PY_INFO = 20;
24constexpr int PY_DEBUG = 10;
25constexpr int PY_NOTSET = 0;
26
27auto pythonLevel(const Message::Priority prio) {
28 switch (prio) {
29 case Message::Priority::PRIO_FATAL:
30 case Message::Priority::PRIO_CRITICAL:
31 return PY_CRITICAL;
32 case Message::Priority::PRIO_ERROR:
33 return PY_ERROR;
34 case Message::Priority::PRIO_WARNING:
35 return PY_WARNING;
36 case Message::Priority::PRIO_NOTICE:
37 case Message::Priority::PRIO_INFORMATION:
38 return PY_INFO;
39 case Message::Priority::PRIO_DEBUG:
40 case Message::Priority::PRIO_TRACE:
41 return PY_DEBUG;
42 default:
43 return PY_NOTSET;
44 }
45}
46
47} // namespace
48
51 auto logger = (boost::python::import("logging").attr("getLogger")("Mantid"));
52 m_pyLogger = std::make_unique<boost::python::object>(std::move(logger));
53}
54
55// The special behavior here is needed because Poco's LoggingFactory can be destroyed
56// after the Python interpreter was shut down.
58 if (Py_IsInitialized()) {
60 // Destroy the object while the GIL is held.
61 m_pyLogger = nullptr;
62 } else {
63 // The Python interpreter has been shut down and our logger object destroyed.
64 // We can no longer safely call the destructor of *m_pLogger,
65 // so just deallocate the memory.
66 operator delete(m_pyLogger.release());
67 }
68}
69
70void PythonLoggingChannel::log(const Poco::Message &msg) {
71 if (m_pyLogger && Py_IsInitialized()) {
73 const auto logFn = m_pyLogger->attr("log");
74 const auto numericLevel = pythonLevel(msg.getPriority());
75 logFn(numericLevel, msg.getText());
76 }
77}
78} // namespace Poco
Defines a structure for acquiring/releasing the Python GIL using the RAII pattern.
std::unique_ptr< boost::python::object > m_pyLogger
void log(const Poco::Message &msg) override
Definition: Algorithm.h:30