0

I'm trying to open a file in pybind11 module and write something into it.

But FILE *fp = fopen("log/module_cc.log", "w"); will return NULL.

Would you please help me with that ?

Actually I'm trying to use spdlog for logging in pybind11 module, and it seems not work as well. I understand the stdout/stderr is not redirect to python module's console, but does file fd is also disabled ?

Here's the spdlog initializer in my pybind11 module:

#include <pybind11/pybind11.h>

PYBIND11_MODULE(my_module, m) {
  // def my module here
}

#include <fmt/format.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/rotating_file_sink.h>


const int MAX_ROTATE_SIZE = 50 * 1024 * 1024;
const int MAX_ROTATE_FILES = 10;
const spdlog::level::level_enum LOG_LEVEL = spdlog::level::info;

struct ModuleInitializer {
  ModuleInitializer() {
    init_logger();
  }

  static void init_logger() {
    auto rotate_logger = spdlog::rotating_logger_mt(
        "my_module", "my_module.log", MAX_ROTATE_SIZE, MAX_ROTATE_FILES);
    spdlog::set_default_logger(rotate_logger);
    spdlog::set_level(LOG_LEVEL);
    spdlog::set_pattern("%Y-%m-%d %H:%M%S.%f | %l | p-%P t-%t | %!:%@ - %v");
    SPDLOG_DEBUG("logging initialized");
  }
};

static ModuleInitializer module_initializer;

Would you please help me with that as well ?

linrongbin
  • 2,967
  • 6
  • 31
  • 59
  • 2
    Does your current working directory have a sub-directory called "log"? If not, that should return `NULL`. – David Schwartz Dec 30 '21 at 02:39
  • @DavidSchwartz, well you are correct, I removed the `log/` prefix and it works! I will try spdlog for file logging again. – linrongbin Dec 30 '21 at 02:49
  • 1
    `fopen()` in C or C++ does not create a complete path. For `fopen("log/module_cc.log", "w")` to succeed, a directory `log` must already exist in your current working directory. If it doesn't, you need to create the directory before calling `fopen()`. – Peter Dec 30 '21 at 02:49
  • To expand on that, you could do something like `std::filesystem::create_directories(std::filesystem::path(YOUR_PATH).parent());` – lionkor Dec 30 '21 at 13:18

0 Answers0