OGS
Logging.cpp
Go to the documentation of this file.
1
12#include "Logging.h"
13
14#include <spdlog/common.h>
15#include <spdlog/sinks/stdout_color_sinks.h>
16#include <spdlog/spdlog.h>
17
18#include <exception>
19#include <iostream>
20#include <map>
21
22#include "Error.h"
23#include "MPI.h"
24
25namespace
26{
27#ifdef USE_PETSC
28static int mpi_rank = -1;
29void mpi_error_handler(const std::string& msg)
30{
31 assert(mpi_rank != -1);
32 std::cerr << "[" << mpi_rank << "] spdlog error: " << msg << std::endl;
33 std::abort();
34}
35#endif // USE_PETSC
36void error_handler(const std::string& msg)
37{
38 std::cerr << "spdlog error: " << msg << std::endl;
39 std::abort();
40}
41} // namespace
42
43namespace BaseLib
44{
45std::shared_ptr<spdlog::logger> console;
46
47void setConsoleLogLevel(std::string const& level_string)
48{
49 using namespace spdlog::level;
50 std::map<std::string, level_enum> string_to_log_level = {
51 {"none", off}, {"critical", critical}, {"error", err}, {"warn", warn},
52 {"info", info}, {"debug", debug}, {"all", trace}};
53
54 auto const level = string_to_log_level.find(level_string);
55 if (level == string_to_log_level.end())
56 {
57 ERR("'{:s}' is not a valid log level!", level_string);
58 OGS_FATAL("Wrong log level string.");
59 }
60 console->set_level(level->second);
61 spdlog::set_default_logger(console);
62}
63
64void initOGSLogger(std::string const& log_level)
65{
66 if (!console)
67 {
68#ifdef USE_PETSC
69 console = spdlog::stdout_color_mt("ogs");
70#else // USE_PETSC
71 console = spdlog::stdout_color_st("ogs");
72#endif // USE_PETSC
73 // Default pattern and error handler both for MPI and non-MPI builds.
74 spdlog::set_pattern("%^%l:%$ %v");
75 spdlog::set_error_handler(error_handler);
76
77#ifdef USE_PETSC
78 int mpi_init;
79 MPI_Initialized(&mpi_init);
80 if (mpi_init == 1)
81 {
82 MPI_Comm_rank(BaseLib::MPI::OGS_COMM_WORLD, &mpi_rank);
83 spdlog::set_pattern(fmt::format("[{}] %^%l:%$ %v", mpi_rank));
84 spdlog::set_error_handler(mpi_error_handler);
85 }
86#endif // USE_PETSC
87 }
89}
90} // namespace BaseLib
#define OGS_FATAL(...)
Definition Error.h:26
void ERR(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:48
MPI_Comm OGS_COMM_WORLD
Definition MPI.cpp:15
void initOGSLogger(std::string const &log_level)
Definition Logging.cpp:64
void setConsoleLogLevel(std::string const &level_string)
Definition Logging.cpp:47
std::shared_ptr< spdlog::logger > console
Definition Logging.cpp:45
void error_handler(const std::string &msg)
Definition Logging.cpp:36
void mpi_error_handler(const std::string &msg)
Definition Logging.cpp:29