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 12 : LogFormatMpiProcess(MPI_Comm comm) : m_comm(comm), m_rank(0) 23 : { 24 12 : MPI_Comm_rank(m_comm, &m_rank); 25 : int size; 26 12 : MPI_Comm_size(m_comm, &size); 27 12 : m_format_width = 1; 28 12 : auto size_cmp = 10; 29 12 : while (size > size_cmp && m_format_width < 9) 30 : { 31 0 : size_cmp *= 10; 32 0 : m_format_width += 1; 33 : } 34 12 : } 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 9 : std::unique_ptr<custom_flag_formatter> clone() const override 46 : { 47 9 : 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 3 : void setup_logging(spdlog::level::level_enum level, MPI_Comm comm) 57 : { 58 3 : spdlog::set_level(level); 59 3 : auto formatter = std::make_unique<spdlog::pattern_formatter>(); 60 3 : formatter->add_flag<ipc::LogFormatMpiProcess>('P', comm); 61 3 : formatter->set_pattern("[MPI %P] [%T] [%^%=8l%$] issm-precice: %v"); 62 3 : spdlog::set_formatter(std::move(formatter)); 63 3 : } 64 : }