The Gaudi Framework  v36r10 (fc05264c)
MessageSvcSink.cpp
Go to the documentation of this file.
1 /***********************************************************************************\
2 * (c) Copyright 1998-2019 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 <string_view>
23 
24 namespace {
25 
38  { "counter", "{0:nEntries|10d}" }, // all unknown counters, and default
39  { "histogram", "{0:nEntries|10d}" }, // all histograms
40  { "counter:AveragingCounter", "{0:nEntries|10d} |{0:sum|11.7g} |{0:mean|#11.5g}" },
41  { "counter:SigmaCounter", "{0:nEntries|10d} |{0:sum|11.7g} |{0:mean|#11.5g} |{0:standard_deviation|#11.5g}" },
42  { "counter:StatCounter", "{0:nEntries|10d} |{0:sum|11.7g} |{0:mean|#11.5g} |{0:standard_deviation|#11.5g} "
43  "|{0:min|#12.5g} |{0:max|#12.5g}" },
44  { "counter:BinomialCounter",
45  "{0:nEntries|10d} |{0:nTrueEntries|11d} |({0:efficiency|#9.7p} +- {0:efficiencyErr|-#8.7p})%" },
46  };
47 
48  // Helper to fix custom formatting of nlohmann::json version 3.10.5
49  // See https://gitlab.cern.ch/gaudi/Gaudi/-/issues/220
50  struct json_fmt_arg {
51  json_fmt_arg( const nlohmann::json& j ) : payload{ j } {}
52  const nlohmann::json& payload;
53  };
54 } // namespace
55 
65 template <>
66 class fmt::formatter<json_fmt_arg> {
67 public:
68  template <typename ParseContext>
69  constexpr auto parse( ParseContext& ctx ) {
70  auto fmt_begin = ctx.begin();
71  auto fmt_end = std::find( fmt_begin, ctx.end(), '}' );
72  if ( fmt_begin == fmt_end ) {
73  // we are dealing with {}, only make sure currentFormat is empty
74  currentFormat = "";
75  } else {
76  // non empty format, let's split name from format
77  auto fmt_colon = std::find( fmt_begin, fmt_end, '|' );
78  currentName = std::string( fmt_begin, fmt_colon - fmt_begin );
79  currentFormat = std::string( fmt_colon + 1, fmt_end - fmt_colon - 1 );
80  }
81  return fmt_end;
82  }
83  template <typename FormatContext>
84  auto format( const json_fmt_arg& json_arg, FormatContext& ctx ) {
85  const auto& j = json_arg.payload;
86  if ( currentFormat.size() == 0 ) {
87  // dealing with {} format, let's find entry for our type in registry
88  const auto type = j.at( "type" ).get<std::string>();
89  // first looking for the entry, then we drop on ":abc" suffix at a time and try again
90  std::string_view type_key{ type };
91  // look for the full entry
92  auto entry = registry.find( type_key );
93  // we check if we have type separators before entering the loop
94  auto sep = type_key.rfind( ':' );
95  while ( sep != type_key.npos && entry == registry.end() ) {
96  // not found, remove the trailing ":abc" section
97  type_key.remove_suffix( type_key.size() - sep );
98  // check if we have another chunk to strip
99  sep = type_key.rfind( ':' );
100  // see if the shorter key works
101  entry = registry.find( type_key );
102  }
103  // if still not found, we use the basic "counter"
104  if ( entry == registry.end() ) entry = registry.find( "counter" );
105  assert( entry != registry.end() );
106  // print the json string according to format found
107  // This actually will call this formatter again a number of times
108  return fmt::format_to( ctx.out(), entry->second, json_arg );
109  } else {
110  // dealing with a {:name|fmt} format
111  auto actualFormat = fmt::format( "{{:{}", currentFormat ) + "}";
112  switch ( currentFormat.back() ) {
113  case 'd':
114  return fmt::format_to( ctx.out(), actualFormat, j.at( currentName ).template get<unsigned int>() );
115  case 'g':
116  return fmt::format_to( ctx.out(), actualFormat, j.at( currentName ).template get<double>() );
117  case 'p':
118  actualFormat[actualFormat.size() - 2] = 'g';
119  return fmt::format_to( ctx.out(), actualFormat, j.at( currentName ).template get<double>() * 100 );
120  default:
121  return fmt::format_to( ctx.out(), "Unknown counter format : {}", currentFormat );
122  }
123  }
124  }
125 
126 private:
129 };
130 
131 namespace {
132 
133  template <typename stream>
134  stream printCounter( stream& log, const std::string& id, const nlohmann::json& j ) {
135  const auto type = j.at( "type" ).get<std::string>();
136  // for backward compatibility, we need to deal with statentity in a special way
137  // this block should be dropped when StatEntities are gone
138  if ( type == "statentity" ) {
139  using boost::algorithm::icontains;
140  bool isBinomial = icontains( id, "eff" ) || icontains( id, "acc" ) || icontains( id, "filt" ) ||
141  icontains( id, "fltr" ) || icontains( id, "pass" );
142  auto nj = j;
143  nj["type"] = isBinomial ? "counter:BinomialCounter" : "counter:StatCounter";
144  return printCounter( log, id, nj );
145  }
146  // binomial counters are slightly different ('*' character)
147  return log << fmt::format( " |{}{:48}|{} |",
148  ( std::string_view{ type }.substr( 0, 23 ) == "counter:BinomialCounter" ? '*' : ' ' ),
149  fmt::format( "\"{}\"", id ), json_fmt_arg{ j } );
150  }
151 
152 } // namespace
153 
154 namespace Gaudi::Monitoring {
155 
158  // only deal with counters, statentity and histograms
159  setProperty( "TypesToSave", std::vector<std::string>{ "counter:.*", "statentity", "histogram:" } )
160  .orThrow( "Unable to set typesToSaveProperty", "Histograming::Sink::Base" );
161  }
163  StatusCode stop() override;
164  };
165 
166  DECLARE_COMPONENT( MessageSvcSink )
167 } // namespace Gaudi::Monitoring
168 
170  // We will try to mimic the old monitoring of counters, so we need to split
171  // them per Algo. The algo name can be extracted form the id of the entity
172  // as its format is "algoName/counterName"
173  // This map groups entities per algoName. For each name, the submap gives
174  // the counter name of each subentity and the associated json
176  // fill the sorted map
177  applytoAllEntities( [&sortedEntities]( auto& ent ) { sortedEntities[ent.component][ent.name] = ent.toJSON(); } );
178  // dump all counters
179  for ( auto& [algoName, entityMap] : sortedEntities ) {
180  // check first whether there is any counter to log
181  unsigned int nbCounters =
182  std::accumulate( begin( entityMap ), end( entityMap ), 0, []( const unsigned int& a, const auto& j ) {
183  return a + ( j.second.at( "empty" ).template get<bool>() ? 0 : 1 );
184  } );
185  if ( 0 == nbCounters ) continue;
186  MsgStream log{ msgSvc(), algoName };
187  log << MSG::INFO << "Number of counters : " << nbCounters << "\n"
188  << " | Counter | # | "
189  << " sum | mean/eff^* | rms/err^* | min | max |";
190  std::for_each( begin( entityMap ), end( entityMap ), [&log]( auto& p ) {
191  // Do not print empty counters
192  if ( !p.second.at( "empty" ).template get<bool>() ) {
193  log << "\n";
194  printCounter( log, p.first, p.second );
195  }
196  } );
197  log << endmsg;
198  }
199  return Service::stop();
200 }
Gaudi::Monitoring::BaseSink
Base class for all Sinks registering to the Monitoring Hub.
Definition: BaseSink.h:27
std::for_each
T for_each(T... args)
Write.stream
stream
Definition: Write.py:32
std::string
STL class.
Gaudi.Configuration.log
log
Definition: Configuration.py:28
MSG::INFO
@ INFO
Definition: IMessageSvc.h:25
MonitoringHub.h
fmt::formatter< json_fmt_arg >::currentFormat
std::string currentFormat
Definition: MessageSvcSink.cpp:127
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
Gaudi::Monitoring
Definition: JSONSink.cpp:19
jsonFromLHCbLog.json
dictionary json
Definition: jsonFromLHCbLog.py:87
GaudiPluginService.cpluginsvc.registry
def registry()
Definition: cpluginsvc.py:84
Gaudi::Monitoring::MessageSvcSink
Definition: MessageSvcSink.cpp:156
GaudiPython.Pythonizations.ctx
ctx
Definition: Pythonizations.py:588
Service::name
const std::string & name() const override
Retrieve name of the service
Definition: Service.cpp:332
StatusCode
Definition: StatusCode.h:65
CLHEP::begin
double * begin(CLHEP::HepVector &v)
Definition: TupleAlg.cpp:45
fmt::formatter< json_fmt_arg >::currentName
std::string currentName
Definition: MessageSvcSink.cpp:128
Gaudi::Monitoring::MessageSvcSink::stop
StatusCode stop() override
stop method, handles the printing
Definition: MessageSvcSink.cpp:169
std::accumulate
T accumulate(T... args)
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
std::map
STL class.
MsgStream
Definition: MsgStream.h:34
IOTest.end
def end
Definition: IOTest.py:128
Gaudi::Monitoring::MessageSvcSink::MessageSvcSink
MessageSvcSink(std::string name, ISvcLocator *svcloc)
Definition: MessageSvcSink.cpp:157
gaudirun.type
type
Definition: gaudirun.py:160
fmt::formatter< json_fmt_arg >::parse
constexpr auto parse(ParseContext &ctx)
Definition: MessageSvcSink.cpp:69
Service::stop
StatusCode stop() override
Definition: Service.cpp:181
DECLARE_COMPONENT
#define DECLARE_COMPONENT(type)
Definition: PluginServiceV1.h:46
BaseSink.h
AsyncIncidents.msgSvc
msgSvc
Definition: AsyncIncidents.py:34
Gaudi::Monitoring::BaseSink::applytoAllEntities
void applytoAllEntities(Callable func, bool sortFirst=false)
applies a callable to all monitoring entities
Definition: BaseSink.h:58
MsgStream.h
fmt::formatter< json_fmt_arg >::format
auto format(const json_fmt_arg &json_arg, FormatContext &ctx)
Definition: MessageSvcSink.cpp:84