Skip to content

Commit

Permalink
Merge pull request #436 from seoklab/python/logging
Browse files Browse the repository at this point in the history
feat(python): log file/line in python
  • Loading branch information
jnooree authored Dec 18, 2024
2 parents 3680a8d + 38b65c3 commit d1586db
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
2 changes: 1 addition & 1 deletion include/nuri/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -853,7 +853,7 @@ inline std::string_view slice_strip(std::string_view str, std::size_t begin,
}

constexpr std::string_view safe_substr(std::string_view str, size_t begin,
size_t count) {
size_t count = std::string_view::npos) {
if (ABSL_PREDICT_FALSE(begin > str.size()))
return {};

Expand Down
19 changes: 16 additions & 3 deletions python/src/nuri/_log_interface_module.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include <absl/log/absl_log.h>
#include <absl/log/globals.h>
#include <absl/log/initialize.h>
#include <absl/log/internal/globals.h>
#include <absl/log/log_entry.h>
#include <absl/log/log_sink.h>
#include <absl/log/log_sink_registry.h>
Expand All @@ -18,6 +19,7 @@
#include <pybind11/pytypes.h>

#include "nuri/meta.h"
#include "nuri/utils.h"

namespace nuri {
namespace python_internal {
Expand Down Expand Up @@ -83,7 +85,9 @@ class PyLogSink: public absl::LogSink {
static absl::once_flag flag;

auto initializer = []() {
absl::InitializeLog();
// abseil/abseil-cpp#1656
if (!absl::log_internal::IsInitialized())
absl::InitializeLog();

logger_ = py::module_::import("logging").attr("getLogger")("nuri");
logger_.inc_ref();
Expand All @@ -92,7 +96,7 @@ class PyLogSink: public absl::LogSink {
NURI_CLANG_ANALYZER_NOLINT absl::AddLogSink(new PyLogSink);
absl::SetStderrThreshold(absl::LogSeverityAtLeast::kFatal);
set_log_level(10);
ABSL_DLOG(INFO) << "initialized NuriKit Python logging sink.";
ABSL_DLOG(INFO) << "Initialized NuriKit Python logging sink.";
};

absl::call_once(flag, initializer);
Expand All @@ -101,8 +105,17 @@ class PyLogSink: public absl::LogSink {
void Send(const absl::LogEntry &entry) override try {
const py::gil_scoped_acquire gil;

// abseil log prefix format (all fixed width before file:line segment)
// 0 1 2 3
// 0 123456789012345678901234567890
// [IWEF]mmdd HH:MM:SS.UUUUUU <thrid> file:line]
//
// We strip off severity, timestamp, and thread id from the prefix because
// Python logging module already provides them (except thread id, which is
// usually not useful for Python users).
try {
logger_.attr("log")(message_loglevel(entry), entry.text_message());
logger_.attr("log")(message_loglevel(entry),
safe_substr(entry.text_message_with_prefix(), 30));
} catch (py::error_already_set &e) {
e.discard_as_unraisable("NuriKit internal logging");
}
Expand Down

0 comments on commit d1586db

Please sign in to comment.