From f50d9f799dec8f1212253c296efc284628edccba Mon Sep 17 00:00:00 2001 From: Kefu Chai Date: Tue, 28 Mar 2017 18:49:01 +0800 Subject: [PATCH] mgr: redirect python stdout,stderr to ceph log PyErr_Print() uses a file object "stderr" for printing messages. Signed-off-by: Kefu Chai --- src/mgr/PyModules.cc | 40 +++++++++++++++++++++++++++++++++++++++- src/mgr/PyModules.h | 1 - 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/mgr/PyModules.cc b/src/mgr/PyModules.cc index 6bb5384ec9bea..e77df011a8c88 100644 --- a/src/mgr/PyModules.cc +++ b/src/mgr/PyModules.cc @@ -29,6 +29,34 @@ #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr + +#undef dout_prefix +#define dout_prefix *_dout << "mgr[py] " + +namespace { + PyObject* log_write(PyObject*, PyObject* args) { + char* m = nullptr; + if (PyArg_ParseTuple(args, "s", &m)) { + auto len = strlen(m); + if (len && m[len-1] == '\n') { + m[len-1] = '\0'; + } + dout(4) << m << dendl; + } + Py_RETURN_NONE; + } + + PyObject* log_flush(PyObject*, PyObject*){ + Py_RETURN_NONE; + } + + static PyMethodDef log_methods[] = { + {"write", log_write, METH_VARARGS, "write stdout and stderr"}, + {"flush", log_flush, METH_VARARGS, "flush"}, + {nullptr, nullptr, 0, nullptr} + }; +} + #undef dout_prefix #define dout_prefix *_dout << "mgr " << __func__ << " " @@ -363,7 +391,17 @@ int PyModules::init() // fake one. This step also picks up site-packages into sys.path. const char *argv[] = {"ceph-mgr"}; PySys_SetArgv(1, (char**)argv); - + + if (g_conf->daemonize) { + auto py_logger = Py_InitModule("ceph_logger", log_methods); +#if PY_MAJOR_VERSION >= 3 + PySys_SetObject("stderr", py_logger); + PySys_SetObject("stdout", py_logger); +#else + PySys_SetObject(const_cast("stderr"), py_logger); + PySys_SetObject(const_cast("stdout"), py_logger); +#endif + } // Populate python namespace with callable hooks Py_InitModule("ceph_state", CephStateMethods); diff --git a/src/mgr/PyModules.h b/src/mgr/PyModules.h index 7ee2a494f6a0d..6c6361a812592 100644 --- a/src/mgr/PyModules.h +++ b/src/mgr/PyModules.h @@ -29,7 +29,6 @@ class PyModules { std::map> modules; std::map> serve_threads; - DaemonStateIndex &daemon_state; ClusterState &cluster_state; MonClient &monc; -- 2.39.5