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