The Gaudi Framework  v37r1 (a7f61348)
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 #if FMT_VERSION < 80000
25 namespace fmt {
26  template <typename T>
27  const T& runtime( const T& v ) {
28  return v;
29  }
30 } // namespace fmt
31 #endif
32 
33 namespace {
34 
47  { "counter", "{0:nEntries|10d}" }, // all unknown counters, and default
48  { "histogram", "{0:nEntries|10d}" }, // all histograms
49  { "counter:AveragingCounter", "{0:nEntries|10d} |{0:sum|11.7g} |{0:mean|#11.5g}" },
50  { "counter:SigmaCounter", "{0:nEntries|10d} |{0:sum|11.7g} |{0:mean|#11.5g} |{0:standard_deviation|#11.5g}" },
51  { "counter:StatCounter", "{0:nEntries|10d} |{0:sum|11.7g} |{0:mean|#11.5g} |{0:standard_deviation|#11.5g} "
52  "|{0:min|#12.5g} |{0:max|#12.5g}" },
53  { "counter:BinomialCounter",
54  "{0:nEntries|10d} |{0:nTrueEntries|11d} |({0:efficiency|#9.7p} +- {0:efficiencyErr|-#8.7p})%" },
55  };
56 
57  // Helper to fix custom formatting of nlohmann::json version 3.10.5
58  // See https://gitlab.cern.ch/gaudi/Gaudi/-/issues/220
59  struct json_fmt_arg {
60  json_fmt_arg( const nlohmann::json& j ) : payload{ j } {}
61  const nlohmann::json& payload;
62  };
63 } // namespace
64 
74 template <>
75 class fmt::formatter<json_fmt_arg> {
76 public:
77  template <typename ParseContext>
78  constexpr auto parse( ParseContext& ctx ) {
79  auto fmt_begin = ctx.begin();
80  auto fmt_end = std::find( fmt_begin, ctx.end(), '}' );
81  if ( fmt_begin == fmt_end ) {
82  // we are dealing with {}, only make sure currentFormat is empty
83  currentFormat = "";
84  } else {
85  // non empty format, let's split name from format
86  auto fmt_colon = std::find( fmt_begin, fmt_end, '|' );
87  currentName = std::string( fmt_begin, fmt_colon - fmt_begin );
88  currentFormat = std::string( fmt_colon + 1, fmt_end - fmt_colon - 1 );
89  }
90  return fmt_end;
91  }
92  template <typename FormatContext>
93  auto format( const json_fmt_arg& json_arg, FormatContext& ctx ) {
94  const auto& j = json_arg.payload;
95  if ( currentFormat.size() == 0 ) {
96  // dealing with {} format, let's find entry for our type in registry
97  const auto type = j.at( "type" ).get<std::string>();
98  // first looking for the entry, then we drop on ":abc" suffix at a time and try again
99  std::string_view type_key{ type };
100  // look for the full entry
101  auto entry = registry.find( type_key );
102  // we check if we have type separators before entering the loop
103  auto sep = type_key.rfind( ':' );
104  while ( sep != type_key.npos && entry == registry.end() ) {
105  // not found, remove the trailing ":abc" section
106  type_key.remove_suffix( type_key.size() - sep );
107  // check if we have another chunk to strip
108  sep = type_key.rfind( ':' );
109  // see if the shorter key works
110  entry = registry.find( type_key );
111  }
112  // if still not found, we use the basic "counter"
113  if ( entry == registry.end() ) entry = registry.find( "counter" );
114  assert( entry != registry.end() );
115  // print the json string according to format found
116  // This actually will call this formatter again a number of times
117  return fmt::format_to( ctx.out(), fmt::runtime( entry->second ), json_arg );
118  } else {
119  // dealing with a {:name|fmt} format
120  auto actualFormat = "{:" + currentFormat + '}';
121  switch ( currentFormat.back() ) {
122  case 'd':
123  return fmt::format_to( ctx.out(), fmt::runtime( actualFormat ),
124  j.at( currentName ).template get<unsigned int>() );
125  case 'g':
126  return fmt::format_to( ctx.out(), fmt::runtime( actualFormat ), j.at( currentName ).template get<double>() );
127  case 'p':
128  actualFormat[actualFormat.size() - 2] = 'g';
129  return fmt::format_to( ctx.out(), fmt::runtime( actualFormat ),
130  j.at( currentName ).template get<double>() * 100 );
131  default:
132  return fmt::format_to( ctx.out(), "Unknown counter format : {}", currentFormat );
133  }
134  }
135  }
136 
137 private:
140 };
141 
142 namespace {
143 
144  template <typename Stream>
145  Stream& printCounter( Stream& log, std::string_view id, const nlohmann::json& j ) {
146  const auto type = j.at( "type" ).get<std::string>();
147  // for backward compatibility, we need to deal with statentity in a special way
148  // this block should be dropped when StatEntities are gone
149  if ( type == "statentity" ) {
150  using boost::algorithm::icontains;
151  bool isBinomial = icontains( id, "eff" ) || icontains( id, "acc" ) || icontains( id, "filt" ) ||
152  icontains( id, "fltr" ) || icontains( id, "pass" );
153  auto nj = j;
154  nj["type"] = isBinomial ? "counter:BinomialCounter" : "counter:StatCounter";
155  return printCounter( log, id, nj );
156  }
157  // binomial counters are slightly different ('*' character)
158  return log << fmt::format( " |{}{:48}|{} |",
159  ( std::string_view{ type }.substr( 0, 23 ) == "counter:BinomialCounter" ? '*' : ' ' ),
160  fmt::format( "\"{}\"", id ), json_fmt_arg{ j } );
161  }
162 
163 } // namespace
164 
165 namespace Gaudi::Monitoring {
166 
176  // only deal with counters, statentity and histograms
177  setProperty( "TypesToSave", std::vector<std::string>{ "counter:.*", "statentity", "histogram:" } )
178  .orThrow( "Unable to set typesToSaveProperty", "Histograming::Sink::Base" );
179  }
181  void flush( bool ) override;
182  };
183 
184  DECLARE_COMPONENT( MessageSvcSink )
185 } // namespace Gaudi::Monitoring
186 
188  // dump all counters
189  for ( auto& [algoName, entityMap] : sortedEntitiesAsJSON() ) {
190  // check first whether there is any counter to log
191  unsigned int nbCounters =
192  std::accumulate( begin( entityMap ), end( entityMap ), 0, []( const unsigned int& a, const auto& j ) {
193  return a + ( j.second.at( "empty" ).template get<bool>() ? 0 : 1 );
194  } );
195  if ( 0 == nbCounters ) continue;
196  MsgStream log{ msgSvc(), algoName };
197  log << MSG::INFO << "Number of counters : " << nbCounters << "\n"
198  << " | Counter | # | "
199  << " sum | mean/eff^* | rms/err^* | min | max |";
200  std::for_each( begin( entityMap ), end( entityMap ), [&log]( auto& p ) {
201  // Do not print empty counters
202  if ( !p.second.at( "empty" ).template get<bool>() ) {
203  log << "\n";
204  printCounter( log, p.first, p.second );
205  }
206  } );
207  log << endmsg;
208  }
209 }
Gaudi::Monitoring::BaseSink
Base class for all Sinks registering to the Monitoring Hub Should be extended by actual Sinks.
Definition: BaseSink.h:40
std::for_each
T for_each(T... args)
std::string
STL class.
Gaudi.Configuration.log
log
Definition: Configuration.py:30
MSG::INFO
@ INFO
Definition: IMessageSvc.h:25
MonitoringHub.h
fmt::formatter< json_fmt_arg >::currentFormat
std::string currentFormat
Definition: MessageSvcSink.cpp:138
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
fmt::runtime
const T & runtime(const T &v)
Definition: MessageSvcSink.cpp:27
jsonFromLHCbLog.json
json
Definition: jsonFromLHCbLog.py:87
Gaudi::Monitoring::MessageSvcSink::flush
void flush(bool) override
stop method, handles the printing
Definition: MessageSvcSink.cpp:187
Gaudi::Monitoring
Definition: JSONSink.cpp:19
GaudiPluginService.cpluginsvc.registry
def registry()
Definition: cpluginsvc.py:84
Gaudi::Monitoring::MessageSvcSink
Sink dedicated to printing messages to the MessageSvc.
Definition: MessageSvcSink.cpp:174
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
ProduceConsume.j
j
Definition: ProduceConsume.py:101
CLHEP::begin
double * begin(CLHEP::HepVector &v)
Definition: TupleAlg.cpp:45
fmt::formatter< json_fmt_arg >::currentName
std::string currentName
Definition: MessageSvcSink.cpp:139
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
Gaudi::Monitoring::MessageSvcSink::MessageSvcSink
MessageSvcSink(std::string name, ISvcLocator *svcloc)
Definition: MessageSvcSink.cpp:175
gaudirun.type
type
Definition: gaudirun.py:162
fmt::formatter< json_fmt_arg >::parse
constexpr auto parse(ParseContext &ctx)
Definition: MessageSvcSink.cpp:78
DECLARE_COMPONENT
#define DECLARE_COMPONENT(type)
Definition: PluginServiceV1.h:46
fmt
Definition: MessageSvcSink.cpp:25
BaseSink.h
Properties.v
v
Definition: Properties.py:123
AsyncIncidents.msgSvc
msgSvc
Definition: AsyncIncidents.py:34
IOTest.end
end
Definition: IOTest.py:123
Gaudi::Monitoring::BaseSink::sortedEntitiesAsJSON
std::map< std::string, std::map< std::string, nlohmann::json > > sortedEntitiesAsJSON() const
returns all entities in JSON format, grouped by component first and then name
Definition: BaseSink.h:108
MsgStream.h
fmt::formatter< json_fmt_arg >::format
auto format(const json_fmt_arg &json_arg, FormatContext &ctx)
Definition: MessageSvcSink.cpp:93