Skip to content

Commit

Permalink
Add a class for Logger
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicolas Cornu committed Sep 12, 2024
1 parent 083b829 commit 28d8ef9
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
6 changes: 4 additions & 2 deletions src/oc/fileio.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
#include <errno.h>
#include "nrnfilewrap.h"

#include "utils/logger.hpp"

extern char* neuron_home;

NrnFILEWrap* hoc_frin;
Expand Down Expand Up @@ -750,11 +752,11 @@ void hoc_Chdir(void) {
}

int nrn_is_python_extension;
int (*nrnpy_pr_stdoe_callback)(int, char*);
Logger logger;
static int (*nrnpy_pass_callback)();

extern "C" void nrnpy_set_pr_etal(int (*cbpr_stdoe)(int, char*), int (*cbpass)()) {
nrnpy_pr_stdoe_callback = cbpr_stdoe;
logger.setCallback(cbpr_stdoe);
nrnpy_pass_callback = cbpass;
}

Expand Down
45 changes: 40 additions & 5 deletions src/utils/logger.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,58 @@

#include <fmt/printf.h>

extern int (*nrnpy_pr_stdoe_callback)(int, char*);
using LoggerCallback = int(int, char*);

class Logger {
public:
void setCallback(LoggerCallback* cb) {
callback = cb;
}

LoggerCallback* getCb() const {
return callback;
}

template <typename ...Args>
void info(const char* fmt, Args... args) {
if (callback) {
std::string message = fmt::format(fmt, std::forward<Args>(args)...);
callback(1, message.data());
}
fmt::print(fmt, std::forward<Args>(args)...);
}

template <typename ...Args>
void error(const char* fmt, Args... args) {
if (callback) {
std::string message = fmt::format(fmt, std::forward<Args>(args)...);
callback(2, message.data());
}
fmt::printf(stderr, fmt, std::forward<Args>(args)...);
}

private:
LoggerCallback* callback;
};

extern Logger logger;

// Deprecated but there is ~700 to change so let it go a bit more
template <typename... Args>
int Fprintf(FILE* stream, const char* fmt, Args... args) {
if (nrnpy_pr_stdoe_callback && (stream == stdout || stream == stderr)) {
if (logger.getCb() && (stream == stdout || stream == stderr)) {
std::string message = fmt::sprintf(fmt, std::forward<Args>(args)...);
nrnpy_pr_stdoe_callback(stream == stdout ? 1 : 2, message.data());
logger.getCb()(stream == stdout ? 1 : 2, message.data());
return message.size();
}
return fmt::fprintf(stream, fmt, args...);
}

template <typename... Args>
int Printf(const char* fmt, Args... args) {
if (nrnpy_pr_stdoe_callback) {
if (logger.getCb()) {
std::string message = fmt::sprintf(fmt, std::forward<Args>(args)...);
nrnpy_pr_stdoe_callback(1, message.data());
logger.getCb()(1, message.data());
return message.size();
}
return fmt::printf(fmt, args...);
Expand Down

0 comments on commit 28d8ef9

Please sign in to comment.