OpenMC/include/openmc/error.h
Andrew Johnson cf763e2477
Add templated write_message for formatting messages
This new function lives inside include/openmc/error.h and
checks if a message will be written by checking the current
verbosity level prior to formatting the message. This works very
similar to python logging modules and the spdlog project, where
the call to the logging function accepts a formattable message
string and the format arguments separately, e.g.

write_message(1, "Writing data for statepoint {}", point)

The function accepts any number and type of argument after the
format message and passes directly to fmt::format and in-turn to
the non-templated write_message. While this later function does
similar checking with the level and MPI rank, the real goal is the
output function in src/error.cpp which is not currently exposed
through the error header file

Thanks to @paulromano for feedback and suggestions
2020-08-06 07:04:59 -04:00

89 lines
1.7 KiB
C++

#ifndef OPENMC_ERROR_H
#define OPENMC_ERROR_H
#include <cstring>
#include <string>
#include <sstream>
#include <fmt/format.h>
#include "openmc/capi.h"
#include "openmc/settings.h"
#ifdef __GNUC__
#define UNREACHABLE() __builtin_unreachable()
#else
#define UNREACHABLE() (void)0
#endif
namespace openmc {
inline void
set_errmsg(const char* message)
{
std::strcpy(openmc_err_msg, message);
}
inline void
set_errmsg(const std::string& message)
{
std::strcpy(openmc_err_msg, message.c_str());
}
inline void
set_errmsg(const std::stringstream& message)
{
std::strcpy(openmc_err_msg, message.str().c_str());
}
[[noreturn]] void fatal_error(const std::string& message, int err=-1);
[[noreturn]] inline
void fatal_error(const std::stringstream& message)
{
fatal_error(message.str());
}
[[noreturn]] inline
void fatal_error(const char* message)
{
fatal_error(std::string{message, std::strlen(message)});
}
void warning(const std::string& message);
inline
void warning(const std::stringstream& message)
{
warning(message.str());
}
void write_message(const std::string& message, int level=0);
inline
void write_message(const std::stringstream& message, int level)
{
write_message(message.str(), level);
}
template<typename... Params>
void write_message(
int level, const std::string& message, const Params&... fmt_args)
{
if (settings::verbosity >= level) {
write_message(fmt::format(message, fmt_args...));
}
}
template<typename... Params>
void write_message(const std::string& message, const Params&... fmt_args)
{
write_message(fmt::format(message, fmt_args...));
}
#ifdef OPENMC_MPI
extern "C" void abort_mpi(int code);
#endif
} // namespace openmc
#endif // OPENMC_ERROR_H