Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

settable log function in python #17

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 48 additions & 2 deletions python/mcache.cc
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
#include <mcache/init.h>
#include <mcache/mcache.h>
#include <mcache/conversion.h>
#include <mcache/logger.h>

// The documentation isn't great, but the name 'borrowed' is a hint. Using
// borrowed instructs boost.python that the PyObject * is a borrowed
Expand Down Expand Up @@ -124,6 +125,50 @@ class atomic_update_fn_t {
boost::python::object fn;
};

static boost::python::object loggerfn;
static log_function_t default_loggerfn;

static void logger(int,
const char *file,
const char *function,
int line,
const char *format, ...)
{
if (!loggerfn) return;
va_list valist;
va_start(valist, format);

// log time and pid -- ignore error
time_t lt = 0;
time(&lt);
char strtime[21] = "notime";
struct tm ltm;
strftime(strtime, sizeof(strtime),
"%Y/%m/%d %H:%M:%S", localtime_r(&lt, &ltm));
fprintf(stderr, "%s [%d] ", strtime, getpid());

// log information
vfprintf(stderr, format, valist);

char buf[2048];

// log place
snprintf(buf, sizeof(buf), " {%s:%s():%d}\n", file, function, line);

va_end(valist);

loggerfn(std::string(buf));
}

static void set_logger(boost::python::object fn) {
loggerfn = fn;
mc::logger = logger;
}

static void set_default_logger() {
mc::logger = default_loggerfn;
loggerfn = boost::python::object();
}

} // namespace

Expand Down Expand Up @@ -557,7 +602,6 @@ struct opts_from_python_dict {
data->convertible = storage;
}
};

} // namespace py
} // namespace mc

Expand All @@ -567,5 +611,7 @@ BOOST_PYTHON_MODULE(mcache) {
mc::py::opts_from_python_dict();
mc::py::client_t<mc::ipc::client_t>::define("Client");
mc::py::client_t<mc::ipc::udp::client_t>::define("UDPClient");
boost::python::def("set_logger", mc::py::set_logger);
boost::python::def("set_default_logger", mc::py::set_default_logger);
mc::py::default_loggerfn = mc::logger;
}

1 change: 0 additions & 1 deletion src/logger.cc
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ static class Initializer_t {
mc::logger = (mc::log_function_t)(dbglog);
} else {
mc::logger = (mc::log_function_t)(stderrLogger);
LOG(INFO3, "DbgLog not found, using stderr logger.");
}
}
} initializer;
Expand Down