Line data Source code
1 : // SPDX-FileCopyrightText: 2024 Daniel Abele <daniel.abele@dlr.de>
2 : //
3 : // SPDX-License-Identifier: BSD-3-Clause
4 :
5 : #include "issm-precice/logging.hpp"
6 : #include "spdlog/common.h"
7 : #include "spdlog/pattern_formatter.h"
8 :
9 : namespace ipc
10 : {
11 :
12 : /**
13 : * spdlog formatter that allows adding the MPI process to log messages.
14 : * See spdlog documentation for
15 : */
16 : class LogFormatMpiProcess : public spdlog::custom_flag_formatter
17 : {
18 : public:
19 : /**
20 : * Create a formatter using the rank in the specified communicator.
21 : */
22 28 : LogFormatMpiProcess(MPI_Comm comm) : m_comm(comm), m_rank(0)
23 : {
24 28 : MPI_Comm_rank(m_comm, &m_rank);
25 : int size;
26 28 : MPI_Comm_size(m_comm, &size);
27 28 : m_format_width = 1;
28 28 : auto size_cmp = 10;
29 28 : while (size > size_cmp && m_format_width < 9)
30 : {
31 0 : size_cmp *= 10;
32 0 : m_format_width += 1;
33 : }
34 28 : }
35 :
36 : /**
37 : * Write the MPI rank to the destination buffer.
38 : */
39 0 : void format(const spdlog::details::log_msg& /*msg*/, const std::tm& /*time*/, spdlog::memory_buf_t& dest) override
40 : {
41 0 : auto rank_string = fmt::format("{0:{1}}", m_rank, m_format_width);
42 0 : dest.append(rank_string.data(), rank_string.data() + rank_string.size());
43 0 : }
44 :
45 21 : std::unique_ptr<custom_flag_formatter> clone() const override
46 : {
47 21 : return spdlog::details::make_unique<LogFormatMpiProcess>(m_comm);
48 : }
49 :
50 : private:
51 : MPI_Comm m_comm;
52 : int m_rank;
53 : int m_format_width;
54 : };
55 :
56 7 : void setup_logging(spdlog::level::level_enum level, MPI_Comm comm)
57 : {
58 7 : spdlog::set_level(level);
59 7 : auto formatter = std::make_unique<spdlog::pattern_formatter>();
60 7 : formatter->add_flag<ipc::LogFormatMpiProcess>('P', comm);
61 14 : formatter->set_pattern("[MPI %P] [%T] [%^%=8l%$] issm-precice: %v");
62 7 : spdlog::set_formatter(std::move(formatter));
63 7 : }
64 : }
|