The Gaudi Framework  v39r0 (5b8b5eda)
MessageSvcSink.cpp
Go to the documentation of this file.
1 /***********************************************************************************\
2 * (c) Copyright 1998-2024 CERN for the benefit of the LHCb and ATLAS collaborations *
3 * *
4 * This software is distributed under the terms of the Apache version 2 licence, *
5 * copied verbatim in the file "LICENSE". *
6 * *
7 * In applying this licence, CERN does not waive the privileges and immunities *
8 * granted to it by virtue of its status as an Intergovernmental Organization *
9 * or submit itself to any jurisdiction. *
10 \***********************************************************************************/
11 
12 #include <Gaudi/BaseSink.h>
13 #include <Gaudi/MonitoringHub.h>
14 #include <GaudiKernel/MsgStream.h>
15 
16 #include <boost/algorithm/string.hpp>
17 
18 #include <fmt/core.h>
19 #include <fmt/format.h>
20 
21 #include <map>
22 #include <sstream>
23 #include <string_view>
24 
25 namespace {
26 
39  { "counter", "{0:nEntries|10d}" }, // all unknown counters, and default
40  { "histogram", "{0:nEntries|10d}" }, // all histograms
41  { "counter:AveragingCounter", "{0:nEntries|10d} |{0:sum|11.7g} |{0:mean|#11.5g}" },
42  { "counter:SigmaCounter", "{0:nEntries|10d} |{0:sum|11.7g} |{0:mean|#11.5g} |{0:standard_deviation|#11.5g}" },
43  { "counter:StatCounter", "{0:nEntries|10d} |{0:sum|11.7g} |{0:mean|#11.5g} |{0:standard_deviation|#11.5g} "
44  "|{0:min|#12.5g} |{0:max|#12.5g}" },
45  { "counter:BinomialCounter",
46  "{0:nEntries|10d} |{0:nTrueEntries|11d} |({0:efficiency|#9.7p} +- {0:efficiencyErr|-#8.7p})%" },
47  };
48 
49  // Helper to fix custom formatting of nlohmann::json version 3.10.5
50  // See https://gitlab.cern.ch/gaudi/Gaudi/-/issues/220
51  struct json_fmt_arg {
52  json_fmt_arg( const nlohmann::json& j ) : payload{ j } {}
53  const nlohmann::json& payload;
54  };
55 } // namespace
56 
66 template <>
67 class fmt::formatter<json_fmt_arg> {
68 public:
69  template <typename ParseContext>
70  constexpr auto parse( ParseContext& ctx ) {
71  auto fmt_begin = ctx.begin();
72  auto fmt_end = std::find( fmt_begin, ctx.end(), '}' );
73  if ( fmt_begin == fmt_end ) {
74  // we are dealing with {}, only make sure currentFormat is empty
75  currentFormat = "";
76  } else {
77  // non empty format, let's split name from format
78  auto fmt_colon = std::find( fmt_begin, fmt_end, '|' );
79  currentName = std::string( fmt_begin, fmt_colon - fmt_begin );
80  currentFormat = std::string( fmt_colon + 1, fmt_end - fmt_colon - 1 );
81  }
82  return fmt_end;
83  }
84  template <typename FormatContext>
85  auto format( const json_fmt_arg& json_arg, FormatContext& ctx ) const {
86  const auto& j = json_arg.payload;
87  if ( currentFormat.size() == 0 ) {
88  // dealing with {} format, let's find entry for our type in registry
89  const auto type = j.at( "type" ).get<std::string>();
90  // first looking for the entry, then we drop on ":abc" suffix at a time and try again
91  std::string_view type_key{ type };
92  // look for the full entry
93  auto entry = registry.find( type_key );
94  // we check if we have type separators before entering the loop
95  auto sep = type_key.rfind( ':' );
96  while ( sep != type_key.npos && entry == registry.end() ) {
97  // not found, remove the trailing ":abc" section
98  type_key.remove_suffix( type_key.size() - sep );
99  // check if we have another chunk to strip
100  sep = type_key.rfind( ':' );
101  // see if the shorter key works
102  entry = registry.find( type_key );
103  }
104  // if still not found, we use the basic "counter"
105  if ( entry == registry.end() ) entry = registry.find( "counter" );
106  assert( entry != registry.end() );
107  // print the json string according to format found
108  // This actually will call this formatter again a number of times
109  return fmt::format_to( ctx.out(), fmt::runtime( entry->second ), json_arg );
110  } else {
111  // dealing with a {:name|fmt} format
112  auto actualFormat = "{:" + currentFormat + '}';
113  switch ( currentFormat.back() ) {
114  case 'd':
115  return fmt::format_to( ctx.out(), fmt::runtime( actualFormat ),
116  j.at( currentName ).template get<unsigned int>() );
117  case 'g':
118  return fmt::format_to( ctx.out(), fmt::runtime( actualFormat ), j.at( currentName ).template get<double>() );
119  case 'p':
120  actualFormat[actualFormat.size() - 2] = 'g';
121  return fmt::format_to( ctx.out(), fmt::runtime( actualFormat ),
122  j.at( currentName ).template get<double>() * 100 );
123  default:
124  return fmt::format_to( ctx.out(), "Unknown counter format : {}", currentFormat );
125  }
126  }
127  }
128 
129 private:
132 };
133 
134 namespace {
135 
136  void printCounter( std::ostringstream& log, std::string_view id, const nlohmann::json& j ) {
137  const auto type = j.at( "type" ).get<std::string>();
138  // for backward compatibility, we need to deal with statentity in a special way
139  // this block should be dropped when StatEntities are gone
140  if ( type == "statentity" ) {
141  using boost::algorithm::icontains;
142  bool isBinomial = icontains( id, "eff" ) || icontains( id, "acc" ) || icontains( id, "filt" ) ||
143  icontains( id, "fltr" ) || icontains( id, "pass" );
144  auto nj = j;
145  nj["type"] = isBinomial ? "counter:BinomialCounter" : "counter:StatCounter";
146  return printCounter( log, id, nj );
147  }
148  // binomial counters are slightly different ('*' character)
149  // fmt::runtime is required when compiling with GCC 11 but
150  // can be dropped when GCC 11 is no longer supported
151  log << fmt::format( fmt::runtime( " |{}{:48}|{} |" ),
152  ( std::string_view{ type }.substr( 0, 23 ) == "counter:BinomialCounter" ? '*' : ' ' ),
153  fmt::format( fmt::runtime( "\"{}\"" ), id ), json_fmt_arg{ j } );
154  }
155 
156 } // namespace
157 
158 namespace Gaudi::Monitoring {
159 
169  // only deal with counters, statentity and histograms
170  setProperty( "TypesToSave", std::vector<std::string>{ "counter:.*", "statentity", "histogram:.*" } )
171  .orThrow( "Unable to set typesToSaveProperty", "Histograming::Sink::Base" );
172  }
174  void flush( bool ) override;
175  };
176 
177  DECLARE_COMPONENT( MessageSvcSink )
178 } // namespace Gaudi::Monitoring
179 
181  std::string curAlgo = "";
182  std::ostringstream curLog;
183  unsigned int nbNonEmptyEntities = 0;
184  auto dumpAlgoCounters = [&]() {
185  // Yes, so print header, dump log and reset counters
186  if ( nbNonEmptyEntities > 0 ) {
187  MsgStream log{ msgSvc(), curAlgo };
188  log << MSG::INFO << "Number of counters : " << nbNonEmptyEntities << "\n"
189  << " | Counter | # | "
190  << " sum | mean/eff^* | rms/err^* | min | max |";
191  log << curLog.str() << endmsg;
192  }
193  };
194  applyToAllSortedEntities( [&]( std::string const& algo, std::string const& entity, nlohmann::json const& j ) {
195  // Did we change to new component ?
196  if ( algo != curAlgo ) {
197  dumpAlgoCounters();
198  curAlgo = algo;
199  nbNonEmptyEntities = 0;
200  curLog = std::ostringstream{};
201  }
202  // is current counter empty ?
203  if ( !j.at( "empty" ).template get<bool>() ) {
204  ++nbNonEmptyEntities;
205  curLog << "\n";
206  printCounter( curLog, entity, j );
207  }
208  } );
209  // last component
210  dumpAlgoCounters();
211 }
Gaudi::Monitoring::BaseSink
Base class for all Sinks registering to the Monitoring Hub Should be extended by actual Sinks.
Definition: BaseSink.h:40
std::string
STL class.
Gaudi.Configuration.log
log
Definition: Configuration.py:28
cpluginsvc.registry
def registry()
Definition: cpluginsvc.py:83
MSG::INFO
@ INFO
Definition: IMessageSvc.h:25
MonitoringHub.h
fmt::formatter< json_fmt_arg >::currentFormat
std::string currentFormat
Definition: MessageSvcSink.cpp:130
std::vector< std::string >
std::find
T find(T... args)
PropertyHolder< CommonMessaging< implements< IService, IProperty, IStateful > > >::setProperty
StatusCode setProperty(const Gaudi::Details::PropertyBase &p)
Set the property from a property.
Definition: IProperty.h:39
ISvcLocator
Definition: ISvcLocator.h:46
jsonFromLHCbLog.json
json
Definition: jsonFromLHCbLog.py:86
Gaudi::Monitoring::MessageSvcSink::flush
void flush(bool) override
stop method, handles the printing
Definition: MessageSvcSink.cpp:180
Gaudi::Monitoring
Definition: JSONSink.cpp:19
AvalancheSchedulerErrorTest.msgSvc
msgSvc
Definition: AvalancheSchedulerErrorTest.py:80
Gaudi::Monitoring::MessageSvcSink
Sink dedicated to printing messages to the MessageSvc.
Definition: MessageSvcSink.cpp:167
GaudiPython.Pythonizations.ctx
ctx
Definition: Pythonizations.py:578
Service::name
const std::string & name() const override
Retrieve name of the service
Definition: Service.cpp:332
ProduceConsume.j
j
Definition: ProduceConsume.py:101
fmt::formatter< json_fmt_arg >::currentName
std::string currentName
Definition: MessageSvcSink.cpp:131
format
GAUDI_API std::string format(const char *,...)
MsgStream format utility "a la sprintf(...)".
Definition: MsgStream.cpp:119
endmsg
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
Definition: MsgStream.h:203
Gaudi::Monitoring::BaseSink::applyToAllSortedEntities
void applyToAllSortedEntities(Callable func) const
applies a callable to all monitoring entities ordered by component the callable will be called once p...
Definition: BaseSink.h:110
std::map
STL class.
MsgStream
Definition: MsgStream.h:34
Gaudi::Monitoring::MessageSvcSink::MessageSvcSink
MessageSvcSink(std::string name, ISvcLocator *svcloc)
Definition: MessageSvcSink.cpp:168
std::ostringstream
STL class.
gaudirun.type
type
Definition: gaudirun.py:160
fmt::formatter< json_fmt_arg >::parse
constexpr auto parse(ParseContext &ctx)
Definition: MessageSvcSink.cpp:70
DECLARE_COMPONENT
#define DECLARE_COMPONENT(type)
Definition: PluginServiceV1.h:46
BaseSink.h
std::ostringstream::str
T str(T... args)
fmt::formatter< json_fmt_arg >::format
auto format(const json_fmt_arg &json_arg, FormatContext &ctx) const
Definition: MessageSvcSink.cpp:85
MsgStream.h