NCBI C++ ToolKit
ncbidiag.hpp
Go to the documentation of this file.

Go to the repository for this file.

1 #ifndef CORELIB___NCBIDIAG__HPP
2 #define CORELIB___NCBIDIAG__HPP
3 
4 /* $Id: ncbidiag.hpp 107538 2026-09-28 14:16:21Z ivanov $
5  * ===========================================================================
6  *
7  * PUBLIC DOMAIN NOTICE
8  * National Center for Biotechnology Information
9  *
10  * This software/database is a "United States Government Work" under the
11  * terms of the United States Copyright Act. It was written as part of
12  * the author's official duties as a United States Government employee and
13  * thus cannot be copyrighted. This software/database is freely available
14  * to the public for use. The National Library of Medicine and the U.S.
15  * Government have not placed any restriction on its use or reproduction.
16  *
17  * Although all reasonable efforts have been taken to ensure the accuracy
18  * and reliability of the software and data, the NLM and the U.S.
19  * Government do not and cannot warrant the performance or results that
20  * may be obtained by using this software or data. The NLM and the U.S.
21  * Government disclaim all warranties, express or implied, including
22  * warranties of performance, merchantability or fitness for any particular
23  * purpose.
24  *
25  * Please cite the author in any work or product based on this material.
26  *
27  * ===========================================================================
28  *
29  * Author: Denis Vakatov
30  *
31  *
32  */
33 
34 /// @file ncbidiag.hpp
35 ///
36 /// Defines NCBI C++ diagnostic APIs, classes, and macros.
37 ///
38 /// More elaborate documentation could be found in:
39 /// http://ncbi.github.io/cxx-toolkit/pages/ch_log.html
40 
41 
42 #include <corelib/ncbi_stack.hpp>
43 #include <deque>
44 #include <vector>
45 #include <map>
46 #include <atomic>
47 #include <stdexcept>
48 
49 
50 /** @addtogroup Diagnostics
51  *
52  * @{
53  */
54 
55 
57 
58 /// Incapsulate compile time information such as
59 /// __FILE__, __LINE__, NCBI_MODULE, current function.
60 /// @note
61 /// NCBI_MODULE is used only in .cpp files
62 /// @sa
63 /// DIAG_COMPILE_INFO
65 {
66 public:
67  // DO NOT create CDiagCompileInfo directly
68  // use macro DIAG_COMPILE_INFO instead!
70  CDiagCompileInfo(void);
72  CDiagCompileInfo(const char* file,
73  int line,
74  const char* curr_funct = NULL,
75  const char* module = NULL);
77  CDiagCompileInfo(const string& file,
78  int line,
79  const string& curr_funct,
80  const string& module);
82  ~CDiagCompileInfo(void);
83 
84  const char* GetFile (void) const;
85  const char* GetModule (void) const;
86  int GetLine (void) const;
87  const string& GetClass (void) const;
88  const string& GetFunction(void) const;
89 
90 private:
91  friend class CNcbiDiag;
92 
93  void SetFile(const string& file);
94  void SetModule(const string& module);
95 
97  void SetLine(int line);
98  // Setting function also sets class if it has not been set explicitly.
99  void SetFunction(const string& func);
100  // Override any class name parsed from function name.
101  void SetClass(const string& cls);
102 
104  void ParseCurrFunctName(void) const;
105 
106  // Check if module needs to be set
107  bool x_NeedModule(void) const;
108 
109  const char* m_File;
110  const char* m_Module;
111  int m_Line;
112 
113  const char* m_CurrFunctName;
114  mutable bool m_Parsed;
115  mutable bool m_ClassSet;
116  mutable string m_ClassName;
117  mutable string m_FunctName;
118 
119  // Storage for data passed as strings rather than char*.
120  string m_StrFile;
121  string m_StrModule;
123 };
124 
125 NCBI_XNCBI_EXPORT const char* g_DiagUnknownFunction(void);
126 
127 /// Get current function name.
128 /// Defined inside of either a method or a function body only.
129 // Based on boost's BOOST_CURRENT_FUNCTION
130 
131 #if defined(__GNUC__) || (defined(__MWERKS__) && (__MWERKS__ >= 0x3000)) || (defined(__ICC) && (__ICC >= 600))
132 # define NCBI_CURRENT_FUNCTION __PRETTY_FUNCTION__
133 #elif defined(__FUNCSIG__)
134 # define NCBI_CURRENT_FUNCTION __FUNCSIG__
135 #elif (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 600)) || (defined(__IBMCPP__) && (__IBMCPP__ >= 500))
136 # define NCBI_CURRENT_FUNCTION __FUNCTION__
137 #elif defined(__BORLANDC__) && (__BORLANDC__ >= 0x550)
138 # define NCBI_CURRENT_FUNCTION __FUNC__
139 #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901)
140 # define NCBI_CURRENT_FUNCTION __func__
141 #else
142 # define NCBI_CURRENT_FUNCTION ncbi::g_DiagUnknownFunction()
143 #endif
144 
145 
146 /// Set default module name based on NCBI_MODULE macro
147 ///
148 /// @sa DIAG_COMPILE_INFO
149 #define NCBI_MAKE_MODULE(module) NCBI_AS_STRING(module)
150 
151 /// Make compile time diagnostic information object
152 /// to use in CNcbiDiag and CException.
153 ///
154 /// This macro along with functionality of macro NCBI_MAKE_MODULE and
155 /// of constructor CDiagCompileInfo ensures that if variable NCBI_MODULE
156 /// will be defined then its value will be used as module name, but if it
157 /// isn't defined then module name in CDiagCompileInfo will be empty.
158 /// "Checking" of definition of NCBI_MODULE is performed at the moment
159 /// of macro issuing so you can define and redefine NCBI_MODULE several
160 /// times during one cpp-file. But BE WARNED that macro NCBI_MODULE is
161 /// considered as not defined when used in any header file. So if you want
162 /// for example make some error posting from inline function defined in
163 /// hpp-file and want your custom module name to be shown in error
164 /// message then you have to use MDiagModule manipulator as following:
165 ///
166 /// ERR_POST_X(1, MDiagModule("MY_MODULE_NAME") << "Error message" );
167 ///
168 /// @sa
169 /// CDiagCompileInfo
170 #define DIAG_COMPILE_INFO \
171  ncbi::CDiagCompileInfo(__FILE__, \
172  __LINE__, \
173  NCBI_CURRENT_FUNCTION, \
174  NCBI_MAKE_MODULE(NCBI_MODULE))
175 
176 
177 
178 /// Error posting with file, line number information but without error codes.
179 /// This macro is deprecated and it's strongly recomended to move
180 /// in all projects (except tests) to macro ERR_POST_X to make possible more
181 /// flexible error statistics and logging.
182 ///
183 /// @sa
184 /// ERR_POST_EX, ERR_POST_X
185 #define ERR_POST(message) \
186  ( ncbi::CNcbiDiag(DIAG_COMPILE_INFO).GetRef() \
187  << message \
188  << ncbi::Endm )
189 
190 /// Wrappers for ERR_POST family of macros checking if the desired
191 /// severity is enabled.
192 ///
193 /// @sa
194 /// ERR_POST, ERR_POST_X, ERR_POST_EX
195 #define SEVERITY_POST(severity, message) \
196  do if (ncbi::IsVisibleDiagPostLevel(ncbi::eDiag_##severity)) \
197  ERR_POST(severity << message); \
198  while(0)
199 #define WARNING_POST(message) SEVERITY_POST(Warning, message)
200 #define INFO_POST(message) SEVERITY_POST(Info, message)
201 #define TRACE_POST(message) SEVERITY_POST(Trace, message)
202 #define SEVERITY_POST_X(severity, subcode, message) \
203  do if (ncbi::IsVisibleDiagPostLevel(ncbi::eDiag_##severity)) \
204  ERR_POST_X(subcode, severity << message); \
205  while(0)
206 #define WARNING_POST_X(subcode, message) SEVERITY_POST_X(Warning, subcode, message)
207 #define INFO_POST_X(subcode, message) SEVERITY_POST_X(Info, subcode, message)
208 #define TRACE_POST_X(subcode, message) SEVERITY_POST_X(Trace, subcode, message)
209 #define SEVERITY_POST_EX(severity, errcode, subcode, message) \
210  do if (ncbi::IsVisibleDiagPostLevel(ncbi::eDiag_##severity)) \
211  ERR_POST_EX(errcode, subcode, severity << message); \
212  while(0)
213 #define WARNING_POST_EX(errcode, subcode, message) SEVERITY_POST_EX(Warning, errcode, subcode, message)
214 #define INFO_POST_EX(errcode, message) SEVERITY_POST_EX(Info, errcode, subcode, message)
215 #define TRACE_POST_EX(errcode, message) SEVERITY_POST_EX(Trace, errcode, subcode, message)
216 
217 // When printing a message in 'old' (human readable) format LOG_POST skips
218 // all fields except the message.
219 /// This macro is deprecated and it's strongly recomended to move
220 /// in all projects (except tests) to macro LOG_POST_X to make possible more
221 /// flexible error statistics and logging.
222 ///
223 /// @sa
224 /// LOG_POST_EX, LOG_POST_X
225 #define LOG_POST(message) \
226  ( ncbi::CNcbiDiag(DIAG_COMPILE_INFO, \
227  ncbi::eDiag_Error, \
228  ncbi::eDPF_Log | ncbi::eDPF_IsNote).GetRef() \
229  << message \
230  << ncbi::Endm )
231 
232 /// Posting fatal error and abort.
233 /// This macro is deprecated and it's strongly recomended to move in all
234 /// projects (except tests) to macro ERR_FATAL_X to make possible more
235 /// flexible error statistics and logging.
236 ///
237 /// @sa
238 /// ERR_FATAL_X, ERR_POST
239 #define ERR_FATAL(message) \
240  ncbi::EndmFatal(ncbi::CNcbiDiag(DIAG_COMPILE_INFO, \
241  ncbi::eDiag_Fatal).GetRef() << message )
242 
243 /// Error posting with error codes.
244 /// This macro should be used only when you need to make non-constant
245 /// error subcode. In all other cases it's strongly recomended to move
246 /// in all projects (except tests) to macro ERR_POST_X to make possible more
247 /// flexible error statistics and logging.
248 ///
249 /// @sa
250 /// ERR_POST, ERR_POST_X
251 #define ERR_POST_EX(err_code, err_subcode, message) \
252  ( ncbi::CNcbiDiag(DIAG_COMPILE_INFO).GetRef() \
253  << ncbi::ErrCode( (err_code), (err_subcode) ) \
254  << message \
255  << ncbi::Endm )
256 
257 #define LOG_POST_EX(err_code, err_subcode, message) \
258  ( ncbi::CNcbiDiag(DIAG_COMPILE_INFO, \
259  ncbi::eDiag_Error, \
260  ncbi::eDPF_Log | ncbi::eDPF_IsNote).GetRef() \
261  << ncbi::ErrCode( (err_code), (err_subcode) ) \
262  << message \
263  << ncbi::Endm )
264 
265 #define ERR_FATAL_EX(err_code, err_subcode, message) \
266  ncbi::EndmFatal(ncbi::CNcbiDiag(DIAG_COMPILE_INFO, \
267  ncbi::eDiag_Fatal).GetRef() << \
268  ncbi::ErrCode( (err_code), (err_subcode) ) << message )
269 
270 /// Define global error code name with given value (err_code) and given
271 /// maximum value of error subcode within this code. To use defined error
272 /// code you need to define symbol NCBI_USE_ERRCODE_X with name as its value.
273 /// This error code is used only in ERR_POST_X macro. Maximum
274 /// value of error subcode is being checked during compilation and
275 /// exists for developers to know what code they can use in next inserted
276 /// ERR_POST_X call (i.e. when one want to insert new ERR_POST_X call he has
277 /// to find definition of error code used in the source file, increase value
278 /// of maximum subcode and put result in ERR_POST_X call).
279 /// Definition of error code and its maximum subcode can be split into 2
280 /// independent macros to avoid recompilation of everything that includes
281 /// header with error code definition. For more information about it see
282 /// NCBI_DEFINE_ERR_SUBCODE_X.
283 /// Macro MUST be used inside ncbi scope.
284 ///
285 /// Example:
286 /// NCBI_DEFINE_ERRCODE_X(Corelib_Util, 110, 5);
287 /// ...
288 /// #define NCBI_USE_ERRCODE_X Corelib_Util
289 /// ...
290 /// ERR_POST_X(3, "My error message with variables " << var);
291 ///
292 ///
293 /// @sa
294 /// NCBI_DEFINE_ERR_SUBCODE_X, ERR_POST_X,
295 /// NCBI_ERRCODE_X, NCBI_MAX_ERR_SUBCODE_X
296 #define NCBI_DEFINE_ERRCODE_X(name, err_code, max_err_subcode) \
297  namespace err_code_x { \
298  enum { \
299  eErrCodeX_##name = err_code, \
300  eErrCodeX_Max_##name = max_err_subcode \
301  }; \
302  template <bool dummy> \
303  struct SErrCodeX_Max_##name { \
304  enum { \
305  value = max_err_subcode, \
306  dumm_dumm = int(dummy) \
307  }; \
308  }; \
309  }
310 
311 /// Define maximum value of subcode for the error code currently in use.
312 /// Currently used error code is defined by macro NCBI_USE_ERRCODE_X. This
313 /// macro is a simplified version of NCBI_DEFINE_ERR_SUBCODE_XX and can be
314 /// handy to use when some error code is used only in one source file and no
315 /// other error code is used in the same source file.
316 /// To use this macro you must put 0 as max_err_subcode in
317 /// NCBI_DEFINE_ERRCODE_X macro. Otherwise compilation error will occur.
318 /// Macro MUST be used inside ncbi scope.
319 ///
320 /// Example:
321 /// NCBI_DEFINE_ERRCODE_X(Corelib_Util, 110, 0);
322 /// ...
323 /// #define NCBI_USE_ERRCODE_X Corelib_Util
324 /// NCBI_DEFINE_ERR_SUBCODE_X(5);
325 /// ...
326 /// ERR_POST_X(3, "My error message with variables " << var);
327 ///
328 ///
329 /// @sa
330 /// NCBI_DEFINE_ERRCODE_X, NCBI_DEFINE_ERR_SUBCODE_XX
331 #define NCBI_DEFINE_ERR_SUBCODE_X(max_err_subcode) \
332  NCBI_DEFINE_ERR_SUBCODE_XX(NCBI_USE_ERRCODE_X, max_err_subcode)
333 
334 /// Define maximum value of subcode for particular error code name.
335 /// To use this macro you must put 0 as max_err_subcode in
336 /// NCBI_DEFINE_ERRCODE_X macro. Otherwise compilation error will occur.
337 /// Macro can be used only once per compilation unit.
338 /// Macro MUST be used inside ncbi scope.
339 ///
340 /// Example:
341 /// NCBI_DEFINE_ERRCODE_X(Corelib_Util, 110, 0);
342 /// ...
343 /// NCBI_DEFINE_ERR_SUBCODE_XX(Corelib_Util, 5);
344 /// ...
345 /// #define NCBI_USE_ERRCODE_X Corelib_Util
346 /// ...
347 /// ERR_POST_X(3, "My error message with variables " << var);
348 ///
349 ///
350 /// @sa
351 /// NCBI_DEFINE_ERRCODE_X
352 #define NCBI_DEFINE_ERR_SUBCODE_XX(name, max_err_subcode) \
353  NCBI_CHECK_ERRCODE_USAGE(name) \
354  namespace err_code_x { \
355  template <> \
356  struct NCBI_NAME2(SErrCodeX_Max_, name)<true> { \
357  enum { \
358  value = max_err_subcode \
359  }; \
360  }; \
361  }
362 
363 
364 /// Returns value of error code by its name defined by NCBI_DEFINE_ERRCODE_X
365 ///
366 /// @sa NCBI_DEFINE_ERRCODE_X
367 #define NCBI_ERRCODE_X_NAME(name) \
368  ncbi::err_code_x::NCBI_NAME2(eErrCodeX_, name)
369 
370 /// Returns currently set default error code. Default error code is set by
371 /// definition of NCBI_USE_ERRCODE_X with name of error code as its value.
372 ///
373 /// @sa NCBI_DEFINE_ERRCODE_X
374 #define NCBI_ERRCODE_X NCBI_ERRCODE_X_NAME(NCBI_USE_ERRCODE_X)
375 
376 /// Returns maximum value of error subcode within error code with given name.
377 ///
378 /// @sa NCBI_DEFINE_ERRCODE_X
379 #define NCBI_MAX_ERR_SUBCODE_X_NAME(name) \
380  ncbi::err_code_x::NCBI_NAME2(SErrCodeX_Max_, name)<true>::value
381 
382 /// Returns maximum value of error subcode within current default error code.
383 ///
384 /// @sa NCBI_DEFINE_ERRCODE_X
385 #define NCBI_MAX_ERR_SUBCODE_X \
386  NCBI_MAX_ERR_SUBCODE_X_NAME(NCBI_USE_ERRCODE_X)
387 
388 
389 /// Template structure used to point out wrong error subcode in
390 /// ERR_POST_X, STD_CATCH_X and alike macros. When error subcode that is
391 /// greater than maximum defined in NCBI_DEFINE_ERRCODE_X or
392 /// NCBI_DEFINE_ERR_SUBCODE_X will be used compiler will give an error and in
393 /// text of this error you'll see the name of this structure. In parameters of
394 /// template instantiation (that will be also shown in error message) you'll
395 /// see error code currently active, error subcode used in *_POST_X macro and
396 /// maximum error subcode valid for active error code.
397 ///
398 /// @sa
399 /// NCBI_DEFINE_ERRCODE_X, NCBI_DEFINE_ERR_SUBCODE_X, ERR_POST_X
400 template <int errorCode, int errorSubcode, int maxErrorSubcode, bool isWrong>
402 
403 /// Specialization of template: when error subcode is valid existence
404 /// of this specialization will be valuable for not issuing compiler error.
405 template <int errorCode, int errorSubcode, int maxErrorSubcode>
407  <errorCode, errorSubcode, maxErrorSubcode, false> {
408  enum {valid = 1};
409 };
410 
411 /// Template structure used to point out incorrect usage of
412 /// NCBI_DEFINE_ERR_SUBCODE_X macro i.e. when it's used for error code defined
413 /// with non-zero maximum subcode in NCBI_DEFINE_ERRCODE_X macro.
414 ///
415 /// @sa
416 /// NCBI_DEFINE_ERRCODE_X, NCBI_DEFINE_ERR_SUBCODE_X
417 template <int errorCode, bool isWrong>
419 
420 /// Specialization of template: when usage of NCBI_DEFINE_ERR_SUBCODE_X is
421 /// correct existence of this specialization will be valuable for not issuing
422 /// compiler error.
423 template <int errorCode>
425  enum {valid = 1};
426 };
427 
428 /// Check that NCBI_DEFINE_ERR_SUBCODE_X is used for correctly defined error
429 /// code.
430 #define NCBI_CHECK_ERRCODE_USAGE(name) \
431  inline void NCBI_NAME2(s_ErrCodeCheck_, name) ( \
432  ncbi::WRONG_USAGE_OF_DEFINE_ERR_SUBCODE_MACRO < \
433  NCBI_ERRCODE_X_NAME(name), \
434  ncbi::err_code_x::eErrCodeX_Max_##name != 0> \
435  /*err_subcode*/) \
436  {}
437 
438 
439 /// Additional dummy function for use in NCBI_CHECK_ERR_SUBCODE_X macro
440 inline void CheckErrSubcodeX(int)
441 {}
442 
443 /// Issue compile-time error if error subcode given is not valid for given
444 /// error code name.
445 /// This design is used for all compilers except early versions of gcc.
446 /// Though for MIPSpro and ICC it's not enough to make error message clear
447 /// (see addition below).
448 ///
449 /// @sa ERR_POST_X
450 #define NCBI_CHECK_ERR_SUBCODE_X_NAME(name, subcode) \
451  ncbi::CheckErrSubcodeX( \
452  (int)sizeof(ncbi::WRONG_ERROR_SUBCODE_IN_POST_MACRO< \
453  NCBI_ERRCODE_X_NAME(name), subcode, \
454  NCBI_MAX_ERR_SUBCODE_X_NAME(name), \
455  ((unsigned int)subcode > \
456  (unsigned int)NCBI_MAX_ERR_SUBCODE_X_NAME(name)) \
457  >) \
458  )
459 
460 /// Issue compile-time error if error subcode given is not valid for current
461 /// error code.
462 #define NCBI_CHECK_ERR_SUBCODE_X(subcode) \
463  NCBI_CHECK_ERR_SUBCODE_X_NAME(NCBI_USE_ERRCODE_X, subcode)
464 
465 /// Pass subcode as argument with check of its validity for given error code.
466 #define NCBI_ERR_SUBCODE_X_NAME(name, subcode) \
467  (NCBI_CHECK_ERR_SUBCODE_X_NAME(name, subcode), subcode)
468 
469 /// Pass subcode as argument with check of its validity for current error code.
470 #define NCBI_ERR_SUBCODE_X(subcode) \
471  (NCBI_CHECK_ERR_SUBCODE_X(subcode), subcode)
472 
473 #if defined(NCBI_COMPILER_ICC)
474 
475 /// Additional not implemented template structure for use in
476 /// WRONG_ERROR_SUBCODE_IN_POST_MACRO structure specialization
477 template <int x>
478 struct WRONG_ERROR_SUBCODE_IN_POST_MACRO_2;
479 
480 /// Specialization of template structure used for ICC and MIPSpro
481 /// If this specialization doesn't exist these compilers doesn't show name
482 /// of unimplemented structure in error message. But when this specialization
483 /// exists and uses recursively another not implemented template structure
484 /// then WRONG_ERROR_SUBCODE_IN_POST_MACRO appears in error message and it
485 /// becomes clearer.
486 template <int errorCode, int errorSubcode, int maxErrorSubcode>
488  <errorCode, errorSubcode, maxErrorSubcode, true> {
489  typedef char t[sizeof(WRONG_ERROR_SUBCODE_IN_POST_MACRO_2<errorCode>)];
490 };
491 
492 /// Additional not implemented template structure for use in
493 /// WRONG_USAGE_OF_DEFINE_ERR_SUBCODE_MACRO structure specialization
494 template <int x>
495 struct WRONG_USAGE_OF_DEFINE_ERR_SUBCODE_MACRO_2;
496 
497 /// Specialization of template structure used for ICC and MIPSpro
498 /// If this specialization doesn't exist these compilers doesn't show name
499 /// of unimplemented structure in error message. But when this specialization
500 /// exists and uses recursively another not implemented template structure
501 /// then WRONG_USAGE_OF_DEFINE_ERR_SUBCODE_MACRO appears in error message and
502 /// it becomes clearer.
503 template <int errorCode>
505  typedef char t[sizeof(
506  WRONG_USAGE_OF_DEFINE_ERR_SUBCODE_MACRO_2<errorCode>)];
507 };
508 
509 #endif // if defined(NCBI_COMPILER_ICC)
510 
511 
512 /// Error posting with default error code and given error subcode. Also
513 /// checks subcode correctness. When error subcode is incorrect (greater than
514 /// defined in NCBI_DEFINE_ERRCODE_X) compile-time error is issued.
515 /// All calls to ERR_POST_X under the same default error code
516 /// MUST be with deferent error subcodes to make possible more
517 /// flexible error statistics and logging.
518 /// If using the macro leads to compile errors containing strings
519 /// like "err_code_x" or "ErrCodeX" in messages, it means you didn't define
520 /// error code name with NCBI_DEFINE_ERRCODE_X macro or didn't select current
521 /// default error code with valid NCBI_USE_ERRCODE_X definition.
522 /// This macro allows the use of only constant error subcodes
523 /// (integer literals or enum constants). If you need to make variable error
524 /// subcode you need to use macro ERR_POST_EX as follows:
525 ///
526 /// NCBI_DEFINE_ERRCODE_X(Corelib_Util, 110, 5);
527 /// ...
528 /// #define NCBI_USE_ERRCODE_X Corelib_Util
529 /// ...
530 /// ERR_POST_EX(NCBI_ERRCODE_X, my_subcode,
531 /// "My error message with variables " << var);
532 ///
533 /// Or in more complicated way:
534 ///
535 /// NCBI_DEFINE_ERRCODE_X(Corelib_Util, 110, 5);
536 /// ...
537 /// // no need to define NCBI_USE_ERRCODE_X
538 /// ...
539 /// ERR_POST_EX(NCBI_ERRCODE_X_NAME(Corelib_Util), my_subcode,
540 /// "My error message with variables " << var);
541 ///
542 /// It's strongly recommended to use macro NCBI_CHECK_ERR_SUBCODE_X
543 /// (or NCBI_CHECK_ERR_SUBCODE_X_NAME in complicated case) to check validity
544 /// of error subcodes in places where variable 'my_subcode' is assigned.
545 ///
546 ///
547 /// @sa NCBI_DEFINE_ERRCODE_X, NCBI_ERRCODE_X, ERR_POST_EX
548 #define ERR_POST_X(err_subcode, message) \
549  ERR_POST_XX(NCBI_USE_ERRCODE_X, err_subcode, message)
550 
551 #define LOG_POST_X(err_subcode, message) \
552  LOG_POST_XX(NCBI_USE_ERRCODE_X, err_subcode, message)
553 
554 #define ERR_FATAL_X(err_subcode, message) \
555  ERR_FATAL_XX(NCBI_USE_ERRCODE_X, err_subcode, message)
556 
557 /// Error posting with error code having given name and with given error
558 /// subcode. Macro must be placed in headers instead of ERR_POST_X to not
559 /// confuse default error codes used in sources where this header is included.
560 ///
561 /// @sa NCBI_DEFINE_ERRCODE_X, ERR_POST_X
562 #define ERR_POST_XX(error_name, err_subcode, message) \
563  ERR_POST_EX(NCBI_ERRCODE_X_NAME(error_name), \
564  NCBI_ERR_SUBCODE_X_NAME(error_name, err_subcode), \
565  message)
566 
567 #define LOG_POST_XX(error_name, err_subcode, message) \
568  LOG_POST_EX(NCBI_ERRCODE_X_NAME(error_name), \
569  NCBI_ERR_SUBCODE_X_NAME(error_name, err_subcode), \
570  message)
571 
572 #define ERR_FATAL_XX(error_name, err_subcode, message) \
573  ERR_FATAL_EX(NCBI_ERRCODE_X_NAME(error_name), \
574  NCBI_ERR_SUBCODE_X_NAME(error_name, err_subcode), \
575  message)
576 
577 /// Common code for making log or error posting only given number of times
578 /// during program execution. This macro MUST not be used outside
579 /// this header.
580 #define NCBI_REPEAT_POST_N_TIMES(post_macro, count, params) \
581  do { \
582  static atomic<int> sx_to_show(count); \
583  int to_show = sx_to_show; \
584  if ( to_show > 0 ) { \
585  sx_to_show = to_show - 1; \
586  post_macro params; /* parenthesis are in params */ \
587  } \
588  } while ( false )
589 
590 
591 /// Error posting only given number of times during program execution.
592 #define ERR_POST_N_TIMES(count, message) \
593  NCBI_REPEAT_POST_N_TIMES( ERR_POST, count, (message) )
594 
595 #define LOG_POST_N_TIMES(count, message) \
596  NCBI_REPEAT_POST_N_TIMES( LOG_POST, count, (message) )
597 
598 
599 /// Error posting only once during program execution.
600 #define ERR_POST_ONCE(message) ERR_POST_N_TIMES(1, message)
601 
602 #define LOG_POST_ONCE(message) LOG_POST_N_TIMES(1, message)
603 
604 
605 /// Error posting only given number of times during program execution
606 /// with default error code and given error subcode.
607 ///
608 /// @sa NCBI_DEFINE_ERRCODE_X, NCBI_ERRCODE_X, ERR_POST_X
609 #define ERR_POST_X_N_TIMES(count, err_subcode, message) \
610  NCBI_REPEAT_POST_N_TIMES( ERR_POST_X, count, (err_subcode, message) )
611 
612 #define LOG_POST_X_N_TIMES(count, err_subcode, message) \
613  NCBI_REPEAT_POST_N_TIMES( LOG_POST_X, count, (err_subcode, message) )
614 
615 /// Error posting only once during program execution with default
616 /// error code and given error subcode.
617 ///
618 /// @sa NCBI_DEFINE_ERRCODE_X, NCBI_ERRCODE_X, ERR_POST_X
619 #define ERR_POST_X_ONCE(err_subcode, message) \
620  ERR_POST_X_N_TIMES(1, err_subcode, message)
621 
622 #define LOG_POST_X_ONCE(err_subcode, message) \
623  LOG_POST_X_N_TIMES(1, err_subcode, message)
624 
625 /// Error posting only given number of times during program execution
626 /// with given error code name and given error subcode.
627 ///
628 /// @sa NCBI_DEFINE_ERRCODE_X, ERR_POST_XX
629 #define ERR_POST_XX_N_TIMES(count, error_name, err_subcode, message) \
630  NCBI_REPEAT_POST_N_TIMES( ERR_POST_XX, count, \
631  (error_name, err_subcode, message) )
632 
633 #define LOG_POST_XX_N_TIMES(count, error_name, err_subcode, message) \
634  NCBI_REPEAT_POST_N_TIMES( LOG_POST_XX, count, \
635  (error_name, err_subcode, message) )
636 
637 /// Error posting only once during program execution with given
638 /// error code name and given error subcode.
639 ///
640 /// @sa NCBI_DEFINE_ERRCODE_X, NCBI_ERRCODE_X, ERR_POST_XX
641 #define ERR_POST_XX_ONCE(error_name, err_subcode, message) \
642  ERR_POST_XX_N_TIMES(1, error_name, err_subcode, message)
643 
644 #define LOG_POST_XX_ONCE(error_name, err_subcode, message) \
645  LOG_POST_XX_N_TIMES(1, error_name, err_subcode, message)
646 
647 /// Severity level for the posted diagnostics.
648 enum EDiagSev {
649  eDiag_Info = 0, ///< Informational message
650  eDiag_Warning, ///< Warning message
651  eDiag_Error, ///< Error message
652  eDiag_Critical, ///< Critical error message
653  eDiag_Fatal, ///< Fatal error -- guarantees exit(or abort)
654  //
655  eDiag_Trace, ///< Trace message
656 
657  // Limits
658  eDiagSevMin = eDiag_Info, ///< Verbosity level for min. severity
659  eDiagSevMax = eDiag_Trace ///< Verbosity level for max. severity
660 };
661 
662 
663 /// Severity level change state.
665  eDiagSC_Unknown, ///< Status of changing severity is unknown (first call)
666  eDiagSC_Disable, ///< Disable change severity level
667  eDiagSC_Enable ///< Enable change severity level
668 };
669 
670 
671 /// Which parts of the diagnostic context should be posted.
672 ///
673 /// Generic appearance of the posted message is as follows:
674 ///
675 /// [<date> <time> ][T<TID> ][["[<path>]/<file>", ][line <line>]: ]
676 /// [<severity>: ][(<err_code>.<err_subcode>) ]
677 /// [<module>[::<class>]::][<function>()] - [<prefix1>::<prefix2>::<prefixN>] <message>\n[
678 /// [<err_code_message>\n]
679 /// [<err_code_explanation>\n]
680 ///
681 /// Example:
682 ///
683 /// - If all flags are set, and prefix string is set to "My prefix", and
684 /// ERR_POST(eDiag_Warning, "Take care!"):
685 /// "/home/iam/myfile.cpp", line 33: Warning: (2.11)
686 /// Module::Class::Function() - [My prefix] Take care!
687 ///
688 /// @sa
689 /// SDiagMessage::Compose()
691  eDPF_File = 1 << 0, ///< File name (not full path)
692  eDPF_LongFilename = 1 << 1, ///< Full file path
693  eDPF_Line = 1 << 2, ///< Source line
694  eDPF_Prefix = 1 << 3, ///< Prefix (default)
695  eDPF_Severity = 1 << 4, ///< Severity (default)
696  eDPF_ErrorID = 1 << 5, ///< Error code and subcode (default)
697 
698  eDPF_DateTime = 1 << 7, ///< Include date and time
699  eDPF_ErrCodeMessage = 1 << 8, ///< Error code message (default)
700  eDPF_ErrCodeExplanation = 1 << 9, ///< Error explanation (default)
701  eDPF_ErrCodeUseSeverity = 1 << 10, ///< Use severity from error code (default)
702  eDPF_Location = 1 << 11, ///< Include class and function if any
703  eDPF_TID = 1 << 13, ///< Thread ID
704 
705  eDPF_PID = 0, ///< @deprecated
706  eDPF_SerialNo = 0, ///< @deprecated
707  eDPF_SerialNo_Thread = 0, ///< @deprecated
708  eDPF_RequestId = 0, ///< @deprecated
709  eDPF_Iteration = eDPF_RequestId, ///< @deprecated
710  eDPF_UID = 0, ///< @deprecated
711 
712  eDPF_ErrCode = eDPF_ErrorID, ///< @deprecated
713  eDPF_ErrSubCode = eDPF_ErrorID, ///< @deprecated
714 
715  /// All flags (except for the "unusual" ones!)
716  eDPF_All = 0x7FFFF,
717 
718  /// Default flags to use when tracing.
719 #if defined(NCBI_THREADS)
722  eDPF_Line |
723  eDPF_Prefix |
724  eDPF_Severity |
725  eDPF_Location |
726  eDPF_PID |
727  eDPF_TID |
728  eDPF_SerialNo |
730 #else
733  eDPF_Line |
734  eDPF_Prefix |
735  eDPF_Severity |
736  eDPF_Location |
737  eDPF_PID |
739 #endif
740 
741  /// Default flags to use for exception formatting.
743 
744  /// Print the posted message only; without severity, location, prefix, etc.
745  eDPF_Log = 0,
746 
747  // "Unusual" flags -- not included in "eDPF_All"
748  eDPF_ErrCodeMsgInFront = 1 << 19, ///< Put ErrCode text in front of the message
749  eDPF_MergeLines = 1 << 21, ///< Escape EOLs.
750  eDPF_PreMergeLines = eDPF_MergeLines, ///< Obsolete. Use eDPF_MergeLines.
751  eDPF_OmitInfoSev = 1 << 22, ///< No sev. indication if eDiag_Info
752  eDPF_OmitSeparator = 1 << 23, ///< No '---' separator before message
753 
754  eDPF_AppLog = 1 << 24, ///< Post message to application log
755  eDPF_IsNote = 1 << 25, ///< Print "Note[X]" severity name.
756  eDPF_IsMessage = eDPF_IsNote, // Legacy name
757 
758  /// This flag is deprecated and ignored - all log writes are atomic.
759  /// For compatibility IsSetDiagPostFlag always returns true when
760  /// asked about this flag.
761  eDPF_AtomicWrite = 1 << 26, ///< @deprecated
762 
763  /// Send the message to 'console' regardless of it's severity.
764  /// To be set by 'Console' manipulator only.
765  eDPF_IsConsole = 1 << 27,
766 
767  /// Use global default flags (merge with).
768  /// @sa SetDiagPostFlag(), UnsetDiagPostFlag(), IsSetDiagPostFlag()
769  eDPF_Default = 1 << 28,
770 
771  /// Important bits which should be taken from the globally set flags
772  /// even if a user attempts to override (or forgets to set) them
773  /// when calling CNcbiDiag().
777 
778  /// Use flags provided by user as-is, do not allow CNcbiDiag to replace
779  /// "important" flags by the globally set ones.
780  eDPF_UseExactUserFlags = 1 << 29
781 };
782 
783 typedef int TDiagPostFlags; ///< Binary OR of "EDiagPostFlag"
784 
785 
786 /// Application execution states shown in the std prefix
788  eDiagAppState_NotSet, ///< Reserved value, never used in messages
795 };
796 
797 
798 // Forward declaration of some classes.
799 class CDiagBuffer;
800 class CDiagErrCodeInfo;
801 
802 
803 
804 /////////////////////////////////////////////////////////////////////////////
805 ///
806 /// ErrCode --
807 ///
808 /// Define composition of error code.
809 ///
810 /// Currently the error code is an ordered pair of <code, subcode> numbers.
811 
812 class ErrCode
813 {
814 public:
815  /// Constructor.
816  ErrCode(int code, int subcode = 0)
817  : m_Code(code), m_SubCode(subcode)
818  { }
819  int m_Code; ///< Major error code number
820  int m_SubCode; ///< Minor error code number
821 };
822 
823 
824 /////////////////////////////////////////////////////////////////////////////
825 ///
826 /// Severity --
827 ///
828 /// Set post severity to a given level.
829 
830 class Severity
831 {
832 public:
834  : m_Level(sev) {}
835  EDiagSev m_Level; ///< Severity level
836 };
837 
838 
839 /////////////////////////////////////////////////////////////////////////////
840 ///
841 /// SetPostFlags --
842 ///
843 /// Set specific post flags.
844 
846 {
847 public:
849  : m_Flags(flags) {}
850  TDiagPostFlags m_Flags; ///< flags to set
851 };
852 
853 
854 class CNcbiDiag;
855 
856 /////////////////////////////////////////////////////////////////////////////
857 ///
858 /// MDiagModule --
859 ///
860 /// Manipulator to set Module for CNcbiDiag
861 
863 {
864 public:
865  MDiagModule(const char* module);
866  friend const CNcbiDiag& operator<< (const CNcbiDiag& diag,
867  const MDiagModule& module);
868 private:
869  const char* m_Module;
870 };
871 
872 
873 
874 /////////////////////////////////////////////////////////////////////////////
875 ///
876 /// MDiagClass --
877 ///
878 /// Manipulator to set Class for CNcbiDiag
879 
881 {
882 public:
883  MDiagClass(const char* nclass);
884  friend const CNcbiDiag& operator<< (const CNcbiDiag& diag,
885  const MDiagClass& nclass);
886 private:
887  const char* m_Class;
888 };
889 
890 
891 
892 /////////////////////////////////////////////////////////////////////////////
893 ///
894 /// MDiagFunction --
895 ///
896 /// Manipulator to set Function for CNcbiDiag
897 
899 {
900 public:
901  MDiagFunction(const char* function);
902  friend const CNcbiDiag& operator<< (const CNcbiDiag& diag,
903  const MDiagFunction& function);
904 private:
905  const char* m_Function;
906 };
907 
908 
909 //
910 class CException;
911 class CStackTrace;
912 
913 
914 /////////////////////////////////////////////////////////////////////////////
915 ///
916 /// CNcbiDiag --
917 ///
918 /// Define the main NCBI Diagnostic class.
919 
920 
922 {
923 public:
924  /// Constructor.
926  (EDiagSev sev = eDiag_Error, ///< Severity level
927  TDiagPostFlags post_flags = eDPF_Default ///< What to post
928  );
929 
930 
931  /// Constructor -- includes the file and line number info
933  (const CDiagCompileInfo& info, ///< File, line, module
934  EDiagSev sev = eDiag_Error, ///< Severity level
935  TDiagPostFlags post_flags = eDPF_Default ///< What to post
936  );
937 
938  /// Destructor.
940 
941  /// Some compilers (e.g. GCC 3.4.0) fail to use temporary objects as
942  /// function arguments if there's no public copy constructor.
943  /// Rather than using the temporary, get a reference from this method.
944  const CNcbiDiag& GetRef(void) const { return *this; }
945 
946  /// Generic method to post to diagnostic stream.
947  template<class X> const CNcbiDiag& Put(const volatile void*, const X& x) const;
948 
949  /// Diagnostic stream manipulator
950  /// @sa Reset(), Endm()
951  /// @sa Info(), Warning(), Error(), Critical(), Fatal(), Trace()
952  typedef const CNcbiDiag& (*FManip)(const CNcbiDiag&);
953  typedef IOS_BASE& (*FIosbaseManip)(IOS_BASE&);
954  typedef CNcbiIos& (*FIosManip)(CNcbiIos&);
955 
956  /// Helper method to post error code and subcode to diagnostic stream.
957  ///
958  /// Example:
959  /// CNcbiDiag() << ErrCode(5,3) << "My message";
960  const CNcbiDiag& Put(const ErrCode*, const ErrCode& err_code) const;
961 
962  /// Helper method to set severity level.
963  ///
964  /// Example:
965  /// CNcbiDiag() << Severity(eDiag_Error) << "My message";
966  const CNcbiDiag& Put(const Severity*, const Severity& severity) const;
967 
968  /// Helper method to post an exception to diagnostic stream.
969  ///
970  /// Example:
971  /// CNcbiDiag() << ex;
972  template<class X> inline
973  const CNcbiDiag& Put(const CException*, const X& x) const {
974  return x_Put(x);
975  }
976 
977  template<class X> inline
978  const CNcbiDiag& Put(const exception*, const X& x) const {
979  const CException* xp = dynamic_cast<const CException*>(&x);
980  if ( xp ) {
981  return x_Put(*xp);
982  }
983  else {
984  string s = x.what();
985  return Put(&s, s);
986  }
987  }
988 
989  /// Helper method to post stack trace to diagnostic stream using
990  /// standard stack trace formatting.
991  ///
992  /// Example:
993  /// CNcbiDiag() << "My message" << CStackTrace();
995  const CNcbiDiag& Put(const CStackTrace*,
996  const CStackTrace& stacktrace) const;
997 
998  /// Helper method to set specific post flags.
999  ///
1000  /// Example:
1001  /// CNcbiDiag() << SetPostFlags(eDPF_DateTime) << "My message";
1002  const CNcbiDiag& Put(const ncbi::SetPostFlags*,
1003  const ncbi::SetPostFlags& flags) const;
1004 
1005  /// Helper method to handle various diagnostic stream manipulators.
1006  ///
1007  /// For example, to set the message severity level to INFO:
1008  /// CNcbiDiag() << Info << "My message";
1009  const CNcbiDiag& Put(const FManip, const FManip& manip) const
1010  {
1011  return manip(*this);
1012  }
1013  inline const CNcbiDiag& operator<< (FManip manip) const
1014  {
1015  return manip(*this);
1016  }
1017  const CNcbiDiag& operator<< (FIosbaseManip manip) const;
1018  const CNcbiDiag& operator<< (FIosManip manip) const;
1019 
1020  /// Post the arguments
1021  /// @sa Put()
1022  template<class X> inline const CNcbiDiag& operator<< (const X& x) const
1023  {
1024  return Put(&x, x);
1025  }
1026 
1027  // Output manipulators for CNcbiDiag.
1028 
1029  /// Reset the content of current message.
1030  friend const CNcbiDiag& Reset (const CNcbiDiag& diag);
1031 
1032  /// Flush current message, start new one.
1033  friend const CNcbiDiag& Endm (const CNcbiDiag& diag);
1034 
1035  /// Flush current message, then set a severity for the next diagnostic
1036  /// message to INFO
1037  friend const CNcbiDiag& Info (const CNcbiDiag& diag);
1038 
1039  /// Flush current message, then set a severity for the next diagnostic
1040  /// message to WARNING
1041  friend const CNcbiDiag& Warning (const CNcbiDiag& diag);
1042 
1043  /// Flush current message, then set a severity for the next diagnostic
1044  /// message to ERROR
1045  friend const CNcbiDiag& Error (const CNcbiDiag& diag);
1046 
1047  /// Flush current message, then set a severity for the next diagnostic
1048  /// message to CRITICAL ERROR
1049  friend const CNcbiDiag& Critical(const CNcbiDiag& diag);
1050 
1051  /// Flush current message, then set a severity for the next diagnostic
1052  /// message to FATAL
1053  friend const CNcbiDiag& Fatal (const CNcbiDiag& diag);
1054 
1055  /// Flush current message, then set a severity for the next diagnostic
1056  /// message to TRACE
1057  friend const CNcbiDiag& Trace (const CNcbiDiag& diag);
1058 
1059  /// Set IsMessage flag to indicate that the current post is a message.
1060  /// Do not flush current post or change the severity. The flag is reset
1061  /// by the next Flush().
1062  /// @deprecated Use Note manipulator.
1063  friend const CNcbiDiag& Message (const CNcbiDiag& diag);
1064 
1065  /// Set IsNote flag to indicate that the current post is a note.
1066  /// Do not flush current post or change the severity. The flag is reset
1067  /// by the next Flush().
1068  friend const CNcbiDiag& Note (const CNcbiDiag& diag);
1069 
1070  /// Set IsConsole flag to indicate that the current post should
1071  /// go to console regardless of its severity (in addition to the
1072  /// default output -- file etc.).
1073  /// Do not flush current post or change the severity. The flag is reset
1074  /// by the next Flush().
1075  friend const CNcbiDiag& Console (const CNcbiDiag& diag);
1076 
1077  /// Print stack trace
1078  friend const CNcbiDiag& StackTrace (const CNcbiDiag& diag);
1079 
1080  /// Get a common symbolic name for the severity levels.
1081  static const char* SeverityName(EDiagSev sev);
1082 
1083  /// Get severity from string.
1084  ///
1085  /// @param str_sev
1086  /// Can be the numeric value or a symbolic name (see
1087  /// CDiagBuffer::sm_SeverityName[]).
1088  /// @param sev
1089  /// Severity level.
1090  /// @return
1091  /// Return TRUE if severity level known; FALSE, otherwise.
1093  static bool StrToSeverityLevel(const char* str_sev, EDiagSev& sev);
1094 
1095  /// Set file name to post.
1097  const CNcbiDiag& SetFile(const char* file) const;
1098 
1099  /// Set module name.
1101  const CNcbiDiag& SetModule(const char* module) const;
1102 
1103  /// Set class name.
1105  const CNcbiDiag& SetClass(const char* nclass) const;
1106 
1107  /// Set function name.
1109  const CNcbiDiag& SetFunction(const char* function) const;
1110 
1111  /// Set line number for post.
1112  const CNcbiDiag& SetLine(size_t line) const;
1113 
1114  /// Set error code and subcode numbers.
1115  const CNcbiDiag& SetErrorCode(int code = 0, int subcode = 0) const;
1116 
1117  /// Get severity of the current message.
1118  EDiagSev GetSeverity(void) const;
1119 
1120  /// Get file used for the current message.
1121  const char* GetFile(void) const;
1122 
1123  /// Get line number for the current message.
1124  size_t GetLine(void) const;
1125 
1126  /// Get error code of the current message.
1127  int GetErrorCode(void) const;
1128 
1129  /// Get error subcode of the current message.
1130  int GetErrorSubCode(void) const;
1131 
1132  /// Get module name of the current message.
1133  const char* GetModule(void) const;
1134 
1135  /// Get class name of the current message.
1136  const char* GetClass(void) const;
1137 
1138  /// Get function name of the current message.
1139  const char* GetFunction(void) const;
1140 
1141  /// Check if filters are passed for the current message.
1142  /// In addition check an exception and all its backlog if specified.
1144  bool CheckFilters(const CException* ex = NULL) const;
1145 
1146  /// Get post flags for the current message.
1147  /// If the post flags have "eDPF_Default" set, then in the returned flags
1148  /// it will be reset and substituted by current default flags.
1150 
1151  /// Set new post flags for the current message.
1153 
1154  /// Set specific post flags for the current message.
1156 
1157  /// Clear specific post flags for the current message.
1159 
1160  /// Display fatal error message.
1161  NCBI_NORETURN NCBI_XNCBI_EXPORT
1162  static void DiagFatal(const CDiagCompileInfo& info,
1163  const char* message);
1164  /// Display trouble error message.
1166  static void DiagTrouble(const CDiagCompileInfo& info,
1167  const char* message = NULL);
1168 
1169  /// Assert specified expression and report results.
1170  NCBI_NORETURN NCBI_XNCBI_EXPORT
1171  static void DiagAssert(const CDiagCompileInfo& info,
1172  const char* expression,
1173  const char* message = NULL);
1174 
1175  /// Same as DiagAssert but only if the system message box is suppressed.
1178  const CDiagCompileInfo& info,
1179  const char* expression,
1180  const char* message = NULL);
1181 
1182  /// Display validation message.
1184  static void DiagValidate(const CDiagCompileInfo& info,
1185  const char* expression,
1186  const char* message);
1187 
1188  /// @deprecated Use ResetIsNoteFlag()
1189  void ResetIsMessageFlag(void) const { ResetIsNoteFlag(); }
1190 
1191  /// Reset IsNote flag.
1192  void ResetIsNoteFlag(void) const { m_PostFlags &= ~eDPF_IsNote; }
1193 
1194  /// Reset IsConsole flag.
1196 
1197  bool GetOmitStackTrace(void) const { return m_OmitStackTrace; }
1199 
1200  /// Set important flags to their globally set values
1201  /// @sa EDiagPostFlags
1203 
1204 private:
1205  mutable EDiagSev m_Severity; ///< Severity level of current msg
1206  mutable int m_ErrCode; ///< Error code
1207  mutable int m_ErrSubCode; ///< Error subcode
1208  CDiagBuffer& m_Buffer; ///< This thread's error msg. buffer
1209  mutable TDiagPostFlags m_PostFlags; ///< Bitwise OR of "EDiagPostFlag"
1210  mutable bool m_OmitStackTrace;
1211 
1213 
1214  /// Private replacement for Endm called from manipulators. Unlike Endm,
1215  /// does not reset ErrCode if buffer is not set.
1216  void x_EndMess(void) const;
1217 
1218  /// Helper func for the exception-related Put()
1219  /// @sa Put()
1220  NCBI_XNCBI_EXPORT const CNcbiDiag& x_Put(const CException& ex) const;
1221 
1222  /// Private copy constructor to prohibit copy.
1224 
1225  /// Private assignment operator to prohibit assignment.
1227 };
1228 
1229 template<> inline const CNcbiDiag& CNcbiDiag::operator<< (const char* const& x) const
1230 {
1231  if (!x) return operator<<("(nil)");
1232  return Put(&x, x);
1233 }
1234 
1235 
1236 /////////////////////////////////////////////////////////////////////////////
1237 // ATTENTION: the following functions are application-wide, i.e they
1238 // are not local for a particular thread
1239 /////////////////////////////////////////////////////////////////////////////
1240 
1241 
1242 /// Check if a specified flag is set.
1243 ///
1244 /// @param flag
1245 /// Flag to check
1246 /// @param flags
1247 /// If eDPF_Default is set for "flags" then use the current global flags on
1248 /// its place (merged with other flags from "flags").
1249 /// @return
1250 /// "TRUE" if the specified "flag" is set in global "flags" that describes
1251 /// the post settings.
1252 /// @sa SetDiagPostFlag(), UnsetDiagPostFlag()
1255 
1256 /// Set global post flags to "flags".
1257 /// If "flags" have flag eDPF_Default set, it will be replaced by the
1258 /// current global post flags.
1259 /// @return
1260 /// Previously set flags
1263 
1264 /// Set the specified flag (globally).
1266 extern void SetDiagPostFlag(EDiagPostFlag flag);
1267 
1268 /// Unset the specified flag (globally).
1270 extern void UnsetDiagPostFlag(EDiagPostFlag flag);
1271 
1272 /// Versions of the above for extra trace flags.
1273 /// ATTENTION: Thus set trace flags will be ADDED to the regular
1274 /// posting flags.
1275 
1278 
1280 extern void SetDiagTraceFlag(EDiagPostFlag flag);
1281 
1283 extern void UnsetDiagTraceFlag(EDiagPostFlag flag);
1284 
1286 
1287 /// Guard for collecting diag messages (affects the current thread only).
1288 ///
1289 /// Messages with the severity equal or above 'print' severity will be
1290 /// printed but not collected. Messages having severity below 'print'
1291 /// severity and equal or above 'collect' severity will be collected,
1292 /// and later can be either discarded or printed out upon the guard
1293 /// destruction or when Release() is called.
1294 /// @note
1295 /// Nested guards are allowed. Each guard takes care to restore the
1296 /// severity thresholds set by the previous one.
1298 {
1299 public:
1300  /// Action to perform in guard's destructor
1301  enum EAction {
1302  ePrint, ///< Print all collected messages as is
1303  eDiscard, ///< Discard collected messages, default
1304  ePrintCapped ///< Print collected messages at reduced severity
1305  };
1306 
1307  /// Set collectable severity and optionally applied print-severity cap
1308  /// to the current post level, Print severity is set to critical.
1309  /// The default action is eDiscard.
1310  CDiagCollectGuard(void);
1311 
1312  /// Set collectable severity and optionally applied print-severity cap
1313  /// to the current post level, Print severity is set to the specified
1314  /// value but can be ignored if it's lower than the currently set post
1315  /// level (or print severity set by a higher level guard). The
1316  /// default action is eDiscard.
1317  CDiagCollectGuard(EDiagSev print_severity);
1318 
1319  /// Create diag collect guard with the given severities and action.
1320  /// As with the other constructor variants, the optionally applied
1321  /// print-severity cap defaults to the collectable severity.
1322  /// The guard will not set print severity below the current diag
1323  /// post level (or print severity of a higher level guard).
1324  /// Collect severity should be equal or lower than the current
1325  /// diag post level or collect severity.
1326  /// The default action is eDiscard.
1327  CDiagCollectGuard(EDiagSev print_severity,
1328  EDiagSev collect_severity,
1329  EAction action = eDiscard);
1330 
1331  /// Destroy the guard, return post level to the one set before the
1332  /// guard initialization. Depending on the currently set action
1333  /// print or discard the messages.
1334  /// On ePrint all collected messages are printed (if there is no
1335  /// higher level guard) and removed from the collection.
1336  /// On eDiscard the messages are silently discarded (only when the
1337  /// last of several nested guards is destroyed).
1338  ~CDiagCollectGuard(void);
1339 
1340  /// Get current print severity
1341  EDiagSev GetPrintSeverity(void) const { return m_PrintSev; }
1342  /// Set new print severity. The new print severity can not be
1343  /// lower than the current one.
1344  void SetPrintSeverity(EDiagSev sev);
1345 
1346  /// Get current collect severity
1347  EDiagSev GetCollectSeverity(void) const { return m_CollectSev; }
1348  /// Set new collect severity. The new collect severity can not be
1349  /// higher than the current one.
1350  void SetCollectSeverity(EDiagSev sev);
1351 
1352  /// Get current severity cap for use in ePrintCapped mode.
1353  EDiagSev GetSeverityCap(void) const { return m_SeverityCap; }
1354  /// Set new severity cap for use in PrintCapped mode.
1355  void SetSeverityCap(EDiagSev sev) { m_SeverityCap = sev; }
1356 
1357  /// Get selected on-destroy action
1358  EAction GetAction(void) const { return m_Action; }
1359  /// Specify on-destroy action.
1360  void SetAction(EAction action) { m_Action = action; }
1361 
1362  /// Get the lowest thread-local post number in this guard's scope.
1363  Uint8 GetStartingPoint(void) const { return m_StartingPoint; }
1364 
1365  /// Release the guard. Perform the currently set action, stop collecting
1366  /// messages, reset severities set by this guard.
1367  void Release(void);
1368 
1369  /// Release the guard. Perform the specified action, stop collecting
1370  /// messages, reset severities set by this guard.
1371  void Release(EAction action);
1372 
1373 private:
1374  void x_Init(EDiagSev print_severity,
1375  EDiagSev collect_severity,
1376  EAction action);
1377 
1383 };
1384 
1385 
1386 /// Specify a string to prefix all subsequent error postings with.
1388 extern void SetDiagPostPrefix(const char* prefix);
1389 
1390 /// Push a string to the list of message prefixes.
1392 extern void PushDiagPostPrefix(const char* prefix);
1393 
1394 /// Pop a string from the list of message prefixes.
1396 extern void PopDiagPostPrefix(void);
1397 
1398 /// Get iteration number/request ID.
1400 extern Uint8 GetDiagRequestId(void);
1401 
1402 /// Set iteration number/request ID.
1404 extern void SetDiagRequestId(Uint8 id);
1405 
1406 
1409 {
1410  return GetDiagRequestId();
1411 }
1412 
1413 
1416 {
1417  SetDiagRequestId(id);
1418 }
1419 
1420 
1421 /////////////////////////////////////////////////////////////////////////////
1422 ///
1423 /// CDiagAutoPrefix --
1424 ///
1425 /// Define the auxiliary class to temporarily add a prefix.
1426 
1428 {
1429 public:
1430  /// Constructor.
1431  CDiagAutoPrefix(const string& prefix);
1432 
1433  /// Constructor.
1434  CDiagAutoPrefix(const char* prefix);
1435 
1436  /// Remove the prefix automagically, when the object gets out of scope.
1437  ~CDiagAutoPrefix(void);
1438 };
1439 
1440 
1441 /// Diagnostic post severity level.
1442 ///
1443 /// The value of DIAG_POST_LEVEL can be a digital value (0-9) or
1444 /// string value from CDiagBuffer::sm_SeverityName[].
1445 #define DIAG_POST_LEVEL "DIAG_POST_LEVEL"
1446 
1447 /// Set the threshold severity for posting the messages.
1448 ///
1449 /// This function has effect only if:
1450 /// - Environment variable $DIAG_POST_LEVEL is not set, and
1451 /// - Registry value of DIAG_POST_LEVEL, section DEBUG is not set
1452 ///
1453 /// Another way to do filtering is to call SetDiagFilter
1454 ///
1455 /// @param post_sev
1456 /// Post only messages with severity greater or equal to "post_sev".
1457 ///
1458 /// Special case: eDiag_Trace -- print all messages and turn on the tracing.
1459 /// @return
1460 /// Return previous post-level.
1461 /// @sa SetDiagFilter(), SetDiagTrace()
1463 extern EDiagSev SetDiagPostLevel(EDiagSev post_sev = eDiag_Error);
1464 
1465 /// Get current threshold severity for posting the messages.
1466 /// @return
1467 /// Return current post-level.
1468 /// @sa SetDiagPostLevel()
1470 extern EDiagSev GetDiagPostLevel(void);
1471 
1472 /// Compare two severities.
1473 /// @return
1474 /// The return value is negative if the first value is lower than
1475 /// the second one, positive if it's higher than the second one,
1476 /// 0 if the severities are equal.
1478 extern int CompareDiagPostLevel(EDiagSev sev1, EDiagSev sev2);
1479 
1480 /// Check if the specified severity is higher or equal to the currently
1481 /// selected post level and will be printed by ERR_POST.
1483 extern bool IsVisibleDiagPostLevel(EDiagSev sev);
1484 
1485 /// Disable change the diagnostic post level.
1486 ///
1487 /// Consecutive using SetDiagPostLevel() will not have effect.
1489 extern bool DisableDiagPostLevelChange(bool disable_change = true);
1490 
1491 /// Sets and locks the level, combining the previous two calls.
1493 extern void SetDiagFixedPostLevel(EDiagSev post_sev);
1494 
1495 /// Set the "die" (abort) level for the program.
1496 ///
1497 /// Abort the application if severity is >= "die_sev".
1498 /// Throw an exception if die_sev is not in the range
1499 /// [eDiagSevMin..eDiag_Fatal].
1500 /// @return
1501 /// Return previous die-level.
1503 extern EDiagSev SetDiagDieLevel(EDiagSev die_sev = eDiag_Fatal);
1504 
1505 /// Get the "die" (abort) level for the program.
1507 extern EDiagSev GetDiagDieLevel(void);
1508 
1509 /// Ignore the die level settings. Return previous setting.
1510 ///
1511 /// WARNING!!! -- not recommended for use unless you are real desperate:
1512 /// By passing TRUE to this function you can make your application
1513 /// never exit/abort regardless of the level set by SetDiagDieLevel().
1514 /// But be warned this is usually a VERY BAD thing to do!
1515 /// -- because any library code counts on at least "eDiag_Fatal" to exit
1516 /// unconditionally, and thus what happens once "eDiag_Fatal" has been posted,
1517 /// is, in general, totally unpredictable! Therefore, use it on your own risk.
1519 extern bool IgnoreDiagDieLevel(bool ignore);
1520 
1521 /// Abort handler function type.
1522 typedef void (*FAbortHandler)(void);
1523 
1524 /// Set/unset abort handler.
1525 ///
1526 /// If "func"==0 use default handler.
1528 extern void SetAbortHandler(FAbortHandler func = 0);
1529 
1530 /// Smart abort function.
1531 ///
1532 /// Processes user abort handler and does not pop up assert windows
1533 /// if specified (environment variable DIAG_SILENT_ABORT is "Y" or "y").
1534 NCBI_NORETURN NCBI_XNCBI_EXPORT
1535 extern void Abort(void);
1536 
1537 /// Diagnostic trace setting.
1538 #define DIAG_TRACE "DIAG_TRACE"
1539 
1540 /// Which setting disables/enables posting of "eDiag_Trace" messages.
1541 ///
1542 /// By default, trace messages are disabled unless:
1543 /// - Environment variable $DIAG_TRACE is set (to any value), or
1544 /// - Registry value of DIAG_TRACE, section DEBUG is set (to any value)
1546  eDT_Default = 0, ///< Restores the default tracing context
1547  eDT_Disable, ///< Ignore messages of severity "eDiag_Trace"
1548  eDT_Enable ///< Enable messages of severity "eDiag_Trace"
1549 };
1550 
1551 
1552 /// Set the diagnostic trace settings.
1554 extern void SetDiagTrace(EDiagTrace how, EDiagTrace dflt = eDT_Default);
1555 
1556 /// Check if traces are enabled.
1558 extern bool GetDiagTrace(void);
1559 
1560 
1561 /// Forward declarations
1562 class CTime;
1563 
1564 /// Internal structure to hold diag message string data.
1565 struct SDiagMessageData;
1566 
1567 struct SDiagMessage;
1568 
1569 /// Callback interface for stream parser. Called for every message read
1570 /// from the input stream.
1571 /// @sa SDiagMessage
1573 {
1574 public:
1575  virtual void operator()(SDiagMessage& msg) = 0;
1576  virtual ~INextDiagMessage(void) {}
1577 };
1578 
1579 
1580 /////////////////////////////////////////////////////////////////////////////
1581 ///
1582 /// SDiagMessage --
1583 ///
1584 /// Diagnostic message structure.
1585 ///
1586 /// Defines structure of the "data" message that is used with message handler
1587 /// function("func"), and destructor("cleanup").
1588 /// The "func(..., data)" to be called when any instance of "CNcbiDiagBuffer"
1589 /// has a new diagnostic message completed and ready to post.
1590 /// "cleanup(data)" will be called whenever this hook gets replaced and
1591 /// on the program termination.
1592 /// NOTE 1: "func()", "cleanup()" and "g_SetDiagHandler()" calls are
1593 /// MT-protected, so that they would never be called simultaneously
1594 /// from different threads.
1595 /// NOTE 2: By default, the errors will be written to standard error stream.
1596 
1598  typedef Uint8 TPID; ///< Process ID
1599  typedef Uint8 TTID; ///< Thread ID
1600  typedef Int8 TUID; ///< Unique process ID
1601 
1602  /// Generic type for counters (posts, requests etc.)
1603  typedef Uint8 TCount;
1604 
1605  /// Initialize SDiagMessage fields.
1606  SDiagMessage(EDiagSev severity, const char* buf, size_t len,
1607  const char* file = 0, size_t line = 0,
1608  TDiagPostFlags flags = eDPF_Default, const char* prefix = 0,
1609  int err_code = 0, int err_subcode = 0,
1610  const char* err_text = 0,
1611  const char* module = 0,
1612  const char* nclass = 0,
1613  const char* function = 0);
1614 
1615  /// Copy constructor required to store the messages and flush them when
1616  /// the diagnostics setup is finished.
1617  SDiagMessage(const SDiagMessage& message);
1618 
1619  /// Assignment of messages
1620  SDiagMessage& operator=(const SDiagMessage& message);
1621 
1622  /// Parse a string back into SDiagMessage. Optional bool argument is
1623  /// set to true if the message was parsed successfully.
1624  SDiagMessage(const string& message, bool* result = 0);
1625 
1626  ~SDiagMessage(void);
1627 
1628  /// Parse the whole string into the message.
1629  /// Return true on success, false if parsing failed.
1630  bool ParseMessage(const string& message);
1631 
1632  /// Stream parser. Reads messages from a stream and calls the callback
1633  /// for each message.
1634  static void ParseDiagStream(CNcbiIstream& in,
1635  INextDiagMessage& func);
1636 
1637  /// Type of event to report
1638  enum EEventType {
1639  eEvent_Start, ///< Application start
1640  eEvent_Stop, ///< Application exit
1641  eEvent_Extra, ///< Other application events
1642  eEvent_RequestStart, ///< Start processing request
1643  eEvent_RequestStop, ///< Finish processing request
1644  eEvent_PerfLog ///< Performance log
1645  };
1646 
1647  static string GetEventName(EEventType event);
1648 
1649  mutable EDiagSev m_Severity; ///< Severity level
1650  const char* m_Buffer; ///< Not guaranteed to be '\0'-terminated!
1651  size_t m_BufferLen; ///< Length of m_Buffer
1652  const char* m_File; ///< File name
1653  const char* m_Module; ///< Module name
1654  const char* m_Class; ///< Class name
1655  const char* m_Function; ///< Function name
1656  size_t m_Line; ///< Line number in file
1657  int m_ErrCode; ///< Error code
1658  int m_ErrSubCode; ///< Sub Error code
1659  TDiagPostFlags m_Flags; ///< Bitwise OR of "EDiagPostFlag"
1660  const char* m_Prefix; ///< Prefix string
1661  const char* m_ErrText; ///< Sometimes 'error' has no numeric code,
1662  ///< but can be represented as text
1663  TPID m_PID; ///< Process ID
1664  TTID m_TID; ///< Thread ID
1665  TCount m_ProcPost; ///< Number of the post in the process
1666  TCount m_ThrPost; ///< Number of the post in the thread
1667  TCount m_RequestId; ///< FastCGI iteration or request ID
1668 
1669  /// If eDPF_AppLog flag is set, m_Event contains event type.
1671 
1672  typedef pair<string, string> TExtraArg;
1673  typedef list<TExtraArg> TExtraArgs;
1674 
1675  /// If event type is "extra", contains the list of arguments
1677  /// Set to true if this is a typed extra message (the arguments include
1678  /// "NCBIEXTRATYPE=<extra-type>").
1680 
1681  /// Special flag indicating that the message should not be printed by
1682  /// Tee-handler.
1683  bool m_NoTee;
1684 
1685  bool m_PrintStackTrace; // Print stack trace after the message
1686 
1687  /// Convert extra arguments to string
1688  string FormatExtraMessage(void) const;
1689 
1690  /// Get UID from current context or parsed from a string
1691  TUID GetUID(void) const;
1692  /// Get time and date - current or parsed.
1693  CTime GetTime(void) const;
1694 
1695  /// Compose a message string in the standard format(see also "flags"):
1696  /// "<file>", line <line>: <severity>: [<prefix>] <message> [EOL]
1697  /// and put it to string "str", or write to an output stream "os".
1698 
1699  /// Which write flags should be output in diagnostic message.
1701  fNone = 0x0, ///< No flags
1702  fNoEndl = 0x01, ///< No end of line
1703  fNoPrefix = 0x02 ///< No std prefix
1704  };
1705 
1706  typedef int TDiagWriteFlags; /// Binary OR of "EDiagWriteFlags"
1707 
1708  /// Write to string.
1709  void Write(string& str, TDiagWriteFlags flags = fNone) const;
1710 
1711  /// Write to stream.
1713 
1714  /// Access to strings stored in SDiagMessageData.
1715  const string& GetHost(void) const;
1716  string GetClient(void) const;
1717  string GetSession(void) const;
1718  const string& GetAppName(void) const;
1719  EDiagAppState GetAppState(void) const;
1720 
1721  CNcbiOstream& x_OldWrite(CNcbiOstream& os, TDiagWriteFlags fl = fNone) const;
1722  CNcbiOstream& x_NewWrite(CNcbiOstream& os, TDiagWriteFlags fl = fNone) const;
1723  string x_GetModule(void) const;
1724 
1725  static void s_EscapeNewlines(string& buf);
1726  static void s_UnescapeNewlines(string& buf);
1727 
1728 private:
1729  // Parse extra args formatted as CGI query string. Do not check validity
1730  // of names and values. Split args by '&', split name/value by '=', do
1731  // URL-decoding.
1732  // If the string is not in the correct format (no '&' or '=') do not
1733  // parse it, return false.
1734  bool x_ParseExtraArgs(const string& str, size_t pos);
1735 
1737  eFormat_Old, // Force old post format
1738  eFormat_New, // Force new post format
1739  eFormat_Auto // Get post format from CDiagContext, default
1740  };
1741  void x_SetFormat(EFormatFlag fmt) const { m_Format = fmt; }
1742  bool x_IsSetOldFormat(void) const;
1743  friend class CDiagContext;
1744 
1745  // Initialize data with the current values
1746  void x_InitData(void) const;
1747  // Save current context properties
1748  void x_SaveContextData(void) const;
1749 
1752 
1753  // Flag indicating if bad symbols in extra argument names are allowed.
1754  // The flag can be set only by CDiagContext_Extra.
1755  friend class CDiagContext_Extra;
1757 };
1758 
1759 /// Insert message in output stream.
1761  return mess.Write(os);
1762 }
1763 
1764 
1765 
1766 /////////////////////////////////////////////////////////////////////////////
1767 ///
1768 /// CDiagContext --
1769 ///
1770 /// NCBI diagnostic context. Storage for application-wide properties.
1771 
1772 class CSpinLock;
1773 class CStopWatch;
1774 class CDiagHandler;
1775 class CNcbiRegistry;
1776 
1777 /// Where to write the application's diagnostics to.
1779  eDS_ToStdout, ///< To standard output stream
1780  eDS_ToStderr, ///< To standard error stream
1781  eDS_ToStdlog, ///< Try standard log file (app.name + ".log") in /log/
1782  ///< and current directory, use stderr if both fail.
1783  eDS_ToMemory, ///< Keep in a temp.memory buffer, see FlushMessages()
1784  eDS_Disable, ///< Don't write it anywhere
1785  eDS_User, ///< Leave as was previously set (or not set) by user
1786  eDS_AppSpecific, ///< Call the application's SetupDiag_AppSpecific()
1787  ///< @deprecated
1788  eDS_Default, ///< Try standard log file (app.name + ".log") in /log/,
1789  ///< use stderr on failure.
1790  eDS_ToSyslog ///< To system log daemon
1791 };
1792 
1793 
1794 /// Flags to control collecting messages and flushing them to the new
1795 /// destination when switching diag handlers.
1797  eDCM_Init, ///< Start collecting messages (with limit), do nothing
1798  ///< if already initialized.
1799  eDCM_InitNoLimit, ///< Start collecting messages without limit (must stop
1800  ///< collecting later using eDCM_Flush or eDCM_Discard).
1801  eDCM_NoChange, ///< Continue collecting messages if already started.
1802  eDCM_Flush, ///< Flush the collected messages and stop collecting.
1803  eDCM_Discard ///< Discard the collected messages without flushing.
1804 };
1805 
1806 
1807 /// Post number increment flag for GetProcessPostNumber() and
1808 /// GetThreadPostNumber().
1810  ePostNumber_NoIncrement, ///< Get post number without incrementing it
1811  ePostNumber_Increment ///< Increment and return the new post number
1812 };
1813 
1814 
1815 class CRequestContext;
1816 class CSharedHitId;
1817 class CRequestRateControl;
1818 class CEncodedString;
1819 
1820 
1821 template<class TKey, class TStorage> class CStrictId;
1822 
1823 /// Temporary object for holding extra message arguments. Prints all
1824 /// of the arguments on destruction.
1826 {
1827 public:
1828  /// Prints all arguments as "name1=value1&name2=value2...".
1829  ~CDiagContext_Extra(void);
1830 
1831  /// The method does not print the argument, but adds it to the string.
1832  /// Name must contain only alphanumeric chars or '_'.
1833  /// Value is URL-encoded before printing.
1834  CDiagContext_Extra& Print(const string& name, const string& value);
1835 
1836  /// Overloaded Print() for all types.
1837  CDiagContext_Extra& Print(const string& name, const char* value);
1838  CDiagContext_Extra& Print(const string& name, int value);
1839  CDiagContext_Extra& Print(const string& name, unsigned int value);
1840  CDiagContext_Extra& Print(const string& name, long value);
1841  CDiagContext_Extra& Print(const string& name, unsigned long value);
1842 #if !NCBI_INT8_IS_LONG
1843  CDiagContext_Extra& Print(const string& name, Int8 value);
1844  CDiagContext_Extra& Print(const string& name, Uint8 value);
1845 #elif SIZEOF_LONG_LONG
1846  CDiagContext_Extra& Print(const string& name, long long value);
1847  CDiagContext_Extra& Print(const string& name, unsigned long long value);
1848 #endif
1849  CDiagContext_Extra& Print(const string& name, char value);
1850  CDiagContext_Extra& Print(const string& name, signed char value);
1851  CDiagContext_Extra& Print(const string& name, unsigned char value);
1852  CDiagContext_Extra& Print(const string& name, double value);
1853  CDiagContext_Extra& Print(const string& name, bool value);
1854  template<class TKey, class TStorage>
1856  {
1857  return Print(name, value.Get());
1858  }
1859 
1860 
1863 
1864  /// The method does not print the arguments, but adds it to the string.
1865  /// Name must contain only alphanumeric chars or '_'.
1866  /// Value is URL-encoded before printing.
1867  /// The args will be modified (emptied) by the function.
1869 
1870  /// Copying the object will prevent printing it on destruction.
1871  /// The new copy should take care of printing.
1873  CDiagContext_Extra& operator=(const CDiagContext_Extra& args);
1874 
1875  /// Print the message and reset object. The object can then be
1876  /// reused to print a new log line (with a new set of arguments
1877  /// if necessary). This is only possible with 'extra' messages,
1878  /// request start/stop messages can not be reused after flush
1879  /// and will print error message instead.
1880  void Flush(void);
1881 
1882  /// Set extra message type.
1883  CDiagContext_Extra& SetType(const string& type);
1884 
1885  /// Allow bad symbols in argument names. URL-encode names the same way
1886  /// as values.
1887  /// NOTE: Avoid using this method if possible. Argument names with
1888  /// encoded symbols may be incompatible with some logging tools.
1889  /// If the flag is not set, any bad symbol is replaced with
1890  /// [ILLEGAL_APPLOG_SYMBOL:%##] string, where %## is the URL-encoded
1891  /// symbol.
1892  CDiagContext_Extra& AllowBadSymbolsInArgNames(void);
1893 
1894 private:
1895  void x_Release(void);
1896  bool x_CanPrint(void);
1897 
1898  // Can be created only by CDiagContext.
1900  // Initialize performance log entry.
1901  CDiagContext_Extra(int status,
1902  double timespan,
1903  TExtraArgs& args);
1904 
1905  // If available, add ncbi_role/ncbi_location to the arguments.
1906  CDiagContext_Extra& PrintNcbiRoleAndLocation(void);
1907  CDiagContext_Extra& PrintNcbiAppInfoOnStart(void);
1908  CDiagContext_Extra& PrintNcbiAppInfoOnRequest(void);
1909 
1910  friend class CDiagContext;
1911  friend NCBI_XNCBI_EXPORT
1912  CDiagContext_Extra g_PostPerf(int status,
1913  double timespan,
1914  SDiagMessage::TExtraArgs& args);
1915 
1919  bool m_Typed;
1920  // PerfLog data
1922  double m_PerfTime;
1925 };
1926 
1927 
1929 {
1930 public:
1931  CDiagContext(void);
1932  ~CDiagContext(void);
1933 
1934  typedef Uint8 TPID;
1935  /// Get cached PID (read real PID if not cached yet).
1936  static TPID GetPID(void);
1937  /// Reset PID cache (e.g. after fork). Return true if PID was updated.
1938  static bool UpdatePID(void);
1939  static bool UpdatePID_AsyncSafe(void);
1940 
1941  /// Actions to perform in UpdateOnFork().
1943  fOnFork_PrintStart = 1 << 0, ///< Log app-start.
1944  fOnFork_ResetTimer = 1 << 1, ///< Reset execution timer.
1945  fOnFork_AsyncSafe = 1 << 15 ///< After a fork() in a multithreaded program, the child can
1946  ///< safely call only async-signal-safe functions. So we can do
1947  ///< only a limited set of operations updating diag context there.
1948  ///< Cancels both previous flags as not async-signal-safe.
1949  };
1950  typedef int TOnForkFlags;
1951 
1952  /// Update diagnostics after fork(). Updates PID if necessary (in the
1953  /// child process). If PID has not changed (parent process), no other
1954  /// actions are performed. For this reason the method will not do anything
1955  /// after the first call, since no PID changes will be detected.
1956  /// @warning
1957  /// The program can be built using multithreaded configurations, but for safety it should
1958  /// have a single thread before fork(). Only in this case it is safe to use any code
1959  /// in the child process.
1960  /// @warning
1961  /// If your program runs many threads and you call fork() one of them, it is safe to use
1962  /// async-safe calls only, otherwise you can get a dedlock, especially if you use thread
1963  /// locking methods and synchronizations, like mutexes and etc.
1964  /// Diag API is not async-safe, because use strings, memory allocations, streams and etc.
1965  /// Also, in such cases you need to use fOnFork_AsyncSafe flag to use async safe operations
1966  /// only inside this method. Note that this flag disable some initialization of the Diag API
1967  /// after forking.
1968  ///
1969  /// @sa UpdatePID(), UpdatePID_AsyncSafe(), CCurrentProcess::GetThreadCount(), CCurrentProcess::Fork()
1970  ///
1971  static void UpdateOnFork(TOnForkFlags flags);
1972 
1974 
1975  /// Return (create if not created yet) unique diagnostic ID.
1976  TUID GetUID(void) const;
1977  /// Return string representation of UID.
1978  /// If the argument UID is 0, use the one from the diag context.
1979  string GetStringUID(TUID uid = 0) const;
1980  /// Take the source UID and replace its timestamp part with the
1981  /// current time.
1982  /// If the source UID is 0, use the one from the diag context.
1983  TUID UpdateUID(TUID uid = 0) const;
1984  /// Fill buffer with string representation of UID. The buffer size
1985  /// must be at least 17 bytes.
1986  void GetStringUID(TUID uid, char* buf, size_t buf_len) const;
1987  /// @deprecated Use GetStringUID(TUID, char*, size_t) instead.
1989  void GetStringUID(TUID uid, char* buf) const;
1990 
1991  /// Create global unique request id.
1992  string GetNextHitID(void) const;
1993  /// Deprecated version of HID generator.
1995  string GetGlobalRequestId(void) const { return GetNextHitID(); }
1996 
1997  /// Shortcut to
1998  /// CDiagContextThreadData::GetThreadData().GetRequestContext()
1999  static CRequestContext& GetRequestContext(void);
2000  /// Shortcut to
2001  /// CDiagContextThreadData::GetThreadData().SetRequestContext()
2002  static void SetRequestContext(CRequestContext* ctx);
2003 
2004  /// Set AutoWrite flag. If set, each property is posted to the current
2005  /// app-log stream when a new value is set.
2006  /// @deprecated
2008  void SetAutoWrite(bool value);
2009 
2010  /// Property visibility flag.
2011  /// @deprecated
2013  eProp_Default, ///< Auto-mode for known properties, local for others
2014  eProp_Global, ///< The property is global for the application
2015  eProp_Thread ///< The property has separate value in each thread
2016  };
2017 
2018  /// Set application context property by name.
2019  /// Write property to the log if AutoPrint flag is set.
2020  /// Property mode defines if the property is a global or a
2021  /// per-thread one. By default unknown properties are set as
2022  /// thread-local.
2023  /// @deprecated
2025  void SetProperty(const string& name,
2026  const string& value,
2027  EPropertyMode mode = eProp_Default);
2028 
2029  /// Get application context property by name, return empty string if the
2030  /// property is not set. If mode is eProp_Default and the property is
2031  /// not a known one, check thread-local properties first.
2032  /// @deprecated
2034  string GetProperty(const string& name,
2035  EPropertyMode mode = eProp_Default) const;
2036 
2037  /// Delete a property by name. If mode is eProp_Default and the property
2038  /// is not a known one, check thread-local properties first.
2039  /// @deprecated
2041  void DeleteProperty(const string& name,
2042  EPropertyMode mode = eProp_Default);
2043 
2044  /// Forced dump of all set properties.
2045  /// @deprecated
2047  void PrintProperties(void);
2048 
2049  /// Global properties
2050  static const char* kProperty_UserName;
2051  static const char* kProperty_HostName;
2052  static const char* kProperty_HostIP;
2053  static const char* kProperty_AppName;
2054  static const char* kProperty_ExitSig;
2055  static const char* kProperty_ExitCode;
2056  /// Per-thread properties
2057  static const char* kProperty_AppState;
2058  static const char* kProperty_ClientIP;
2059  static const char* kProperty_SessionID;
2060  static const char* kProperty_ReqStatus;
2061  static const char* kProperty_ReqTime;
2062  static const char* kProperty_BytesRd;
2063  static const char* kProperty_BytesWr;
2064 
2065  /// Print start/stop etc. message. If the following values are set as
2066  /// properties, they will be dumped before the message:
2067  /// host | host_ip_addr
2068  /// client_ip
2069  /// session_id
2070  /// app_name
2071  /// All messages have the following prefix:
2072  /// PID/TID/ITER UID TIME HOST CLIENT SESSION_ID APP_NAME
2073  /// Depending on its type, a message can be prefixed with the following
2074  /// properties if they are set:
2075  /// start
2076  /// stop [SIG] [EXIT_CODE] ELAPSED_TIME
2077  /// extra
2078  /// request-start
2079  /// request-stop [STATUS] [REQ_ELAPSED_TIME] [BYTES_RD] [BYTES_WR]
2080  void PrintStart(const string& message);
2081 
2082  /// Print exit message.
2083  void PrintStop(void);
2084 
2085  /// Print extra message in plain text format.
2086  /// This method is deprecated and should be replaced by a call to
2087  /// Extra() method and one or more calls to CDiagContext_Extra::Print().
2088  NCBI_DEPRECATED void PrintExtra(const string& message);
2089 
2090  /// Create a temporary CDiagContext_Extra object. The object will print
2091  /// arguments automatically from destructor. Can be used like:
2092  /// Extra().Print(name1, val1).Print(name2, val2);
2094  {
2096  }
2097 
2098  /// Print request start message (for request-driven applications)
2099  /// @deprecated Use CDiagContext_Extra version.
2100  NCBI_DEPRECATED void PrintRequestStart(const string& message);
2101  /// Create a temporary CDiagContext_Extra object. The object will print
2102  /// arguments automatically from destructor. Can be used like:
2103  /// PrintRequestStart().Print(name1, val1).Print(name2, val2);
2104  CDiagContext_Extra PrintRequestStart(void);
2105 
2106  /// Print request stop message (for request-driven applications)
2107  void PrintRequestStop(void);
2108 
2109  /// Always returns global application state.
2110  EDiagAppState GetGlobalAppState(void) const;
2111  /// Set global application state.
2112  /// Do not change state of the current thread.
2113  void SetGlobalAppState(EDiagAppState state);
2114  /// Return application state for the current thread if it's set.
2115  /// If not set, return global application state. This is a shortcut
2116  /// to the current request context's GetAppState().
2117  EDiagAppState GetAppState(void) const;
2118  /// Set application state. Application state is set globally and the
2119  /// thread's state is reset (for the current thread only).
2120  /// Request states are set for the current thread (request context) only.
2121  void SetAppState(EDiagAppState state);
2122  /// The 'mode' flag is deprecated. Use CRequestContext::SetAppState() for
2123  /// per-thread/per-request state.
2125  void SetAppState(EDiagAppState state, EPropertyMode mode);
2126 
2127  /// Check old/new format flag (for compatibility only)
2128  static bool IsSetOldPostFormat(void);
2129  /// Set old/new format flag
2130  static void SetOldPostFormat(bool value);
2131 
2132  /// Check if system TID is printed instead of CThread::GetSelf()
2133  static bool IsUsingSystemThreadId(void);
2134  /// Switch printing system TID (rather than CThread::GetSelf()) on/off
2135  static void UseSystemThreadId(bool value = true);
2136 
2137  /// Get username
2138  const string& GetUsername(void) const;
2139  /// Set username
2140  /// @sa SetDiagUserAndHost
2141  void SetUsername(const string& username);
2142 
2143  /// Get host name. The order is: cached hostname, cached hostIP,
2144  /// uname or COMPUTERNAME, SERVER_ADDR, empty string.
2145  const string& GetHost(void) const;
2146  /// URL-encoded version of GetHost()
2147  const string& GetEncodedHost(void) const;
2148 
2149  /// Get cached hostname - do not try to detect host name as GetHost() does.
2150  const string& GetHostname(void) const;
2151  /// Get URL-encoded hostname
2152  const string& GetEncodedHostname(void) const;
2153  /// Set hostname
2154  /// @sa SetDiagUserAndHost
2155  void SetHostname(const string& hostname);
2156 
2157  /// Get host IP address
2158  const string& GetHostIP(void) const { return m_HostIP; }
2159  /// Set host IP address
2160  void SetHostIP(const string& ip);
2161 
2162  /// Get application name
2163  const string& GetAppName(void) const;
2164  /// Get URL-encoded application name
2165  const string& GetEncodedAppName(void) const;
2166  /// Set application name
2167  void SetAppName(const string& app_name);
2168 
2169  /// Check if exit code has been set.
2170  bool IsSetExitCode(void) const { return m_ExitCodeSet; }
2171  /// Get exit code
2172  int GetExitCode(void) const { return m_ExitCode; }
2173  /// Set exit code
2174  void SetExitCode(int exit_code)
2175  {
2176  m_ExitCode = exit_code;
2177  m_ExitCodeSet = true;
2178  }
2179 
2180  /// Get exit signal
2181  int GetExitSignal(void) const { return m_ExitSig; }
2182  /// Set exit signal
2183  void SetExitSignal(int exit_sig) { m_ExitSig = exit_sig; }
2184 
2185  /// Get default session id. The session id may be set using
2186  /// SetDefaultSessionId(), NCBI_LOG_SESSION_ID env. variable
2187  /// or Log.Session_Id value in the INI file.
2188  string GetDefaultSessionID(void) const;
2189  /// Set new default session id. This value is used only if the per-request
2190  /// session id is not set.
2191  void SetDefaultSessionID(const string& session_id);
2192  /// Get the effective session id: the per-request session id if set,
2193  /// or the default session id.
2194  string GetSessionID(void) const;
2195  /// Get url-encoded session id.
2196  string GetEncodedSessionID(void) const;
2197 
2198  /// Get default client ip. The ip may be set using SetDefaultClientIP(),
2199  /// NCBI_LOG_CLIENT_IP env. variable or Log.Client_Ip value in the INI
2200  /// file.
2201  static string GetDefaultClientIP(void);
2202  /// Set new default client ip. This value is used only if by the time
2203  /// 'request start' is logged there's no explicit ip set in the current
2204  /// request context.
2205  static void SetDefaultClientIP(const string& client_ip);
2206 
2207  /// Get global default hit id. The hit id may be set using
2208  /// SetDefaultHitId(), HTTP_NCBI_PHID or NCBI_LOG_HIT_ID env. variables,
2209  /// or Log.Http_Hit_Id/Log.Hit_Id values in the INI file. The Http-value
2210  /// has higher priority. If none of the values is set, the default hit id
2211  /// is generated automatically.
2212  string GetDefaultHitID(void) const;
2213 
2214  /// Set new global default hit id. This value is used only if the per-request
2215  /// hit id is not set.
2216  void SetDefaultHitID(const string& hit_id);
2217 
2218  /// Get host role (DEV/QA/TRY/PROD) from /etc/ncbi/role.
2219  static const string& GetHostRole(void);
2220 
2221  /// Get host location (be-md/st-va) from /etc/ncbi/location.
2222  static const string& GetHostLocation(void);
2223 
2224  /// Write standard prefix to the stream. Use values from the message
2225  /// (PID/TID/RID etc.).
2226  void WriteStdPrefix(CNcbiOstream& ostr,
2227  const SDiagMessage& msg) const;
2228 
2229  /// Start collecting all messages (the collected messages can be flushed
2230  /// to a new destination later). Stop collecting messages when max_size
2231  /// is reached.
2232  void InitMessages(size_t max_size = 100);
2233  /// Save new message
2234  void PushMessage(const SDiagMessage& message);
2235  /// Flush the collected messages to the current diag handler.
2236  /// Does not clear the collected messages.
2237  void FlushMessages(CDiagHandler& handler);
2238  /// Discard the collected messages without printing them.
2239  void DiscardMessages(void);
2240  /// Check if message collecting is on
2241  bool IsCollectingMessages(void) const { return m_Messages.get() != 0; }
2242 
2243  /// Get log file truncation flag
2244  static bool GetLogTruncate(void);
2245  /// Set log file truncation flag
2246  static void SetLogTruncate(bool value);
2247 
2248  /// @depracated The flag is always set now, the funcion still calls
2249  /// SetupDiag() for compatibility, but has no other effects.
2250  NCBI_DEPRECATED static void SetUseRootLog(void);
2251 
2252  /// Check if the current diagnostics destination is /log/*
2253  static bool IsUsingRootLog(void);
2254 
2255  /// Application-wide diagnostics setup. Attempts to create log files
2256  /// or diag streams according to the 'ds' flag. If 'config' is set,
2257  /// gets name of the log file from the registry.
2258  static void SetupDiag(EAppDiagStream ds = eDS_Default,
2261  const char* cmd_logfile = NULL);
2262 
2264  /// Return process post number (incrementing depends on the flag).
2265  static TCount GetProcessPostNumber(EPostNumberIncrement inc);
2266  /// Return thread post number (incrementing depends on the flag).
2267  static TCount GetThreadPostNumber(EPostNumberIncrement inc);
2268 
2269  /// Get thread ID used in messages
2270  typedef Uint8 TTID;
2271  static TTID GetTID(void);
2272 
2273  /// Type of logging rate limit
2275  eLogRate_App, ///< Application log
2276  eLogRate_Err, ///< Error log
2277  eLogRate_Trace ///< Trace log
2278  };
2279 
2280  /// Logging rate control - max number of messages per period.
2281  unsigned int GetLogRate_Limit(ELogRate_Type type) const;
2282  void SetLogRate_Limit(ELogRate_Type type, unsigned int limit);
2283 
2284  /// Logging rate control - the messages control period, seconds.
2285  unsigned int GetLogRate_Period(ELogRate_Type type) const;
2286  void SetLogRate_Period(ELogRate_Type type, unsigned int period);
2287 
2288  /// Internal function, should be used only by CNcbiApplication.
2289  static void x_FinalizeSetupDiag(void);
2290 
2291  /// When using applog, the diag post level is locked to Warning.
2292  /// The following functions allow to access the lock, but should
2293  /// not be used by most applications.
2294  static bool IsApplogSeverityLocked(void)
2295  { return sm_ApplogSeverityLocked; }
2296  static void SetApplogSeverityLocked(bool lock)
2297  { sm_ApplogSeverityLocked = lock; }
2298 
2299  static bool IsMainThreadDataInitialized(void);
2300 
2301  /// Get flag disabling applog events (set by DIAG_DISABLE_APPLOG_MESSAGES variable).
2302  static bool GetDisabledAppLog(void);
2303 
2304  /// Flags for disabling groups of applog events with DIAG_DISABLE_APPLOG_MESSAGES.
2305  /// The global value can be set using DIAG_DISABLE_APPLOG_MESSAGE_TYPES.
2307  eDisable_All, ///< Disable all applog events (default).
2308  eEnable_App ///< Allow only application start/stop.
2309  };
2310  /// Get disabled applog events (set by DIAG_DISABLE_APPLOG_MESSAGE_TYPES variable).
2311  static EDisabledAppLogEvents GetDisabledAppLogEvents(void);
2312 
2313 private:
2316 
2317  // Initialize UID
2318  void x_CreateUID(void) const;
2319  void x_CreateUID_AsyncSafe(void) const;
2320 
2321  // Write message to the log using current handler
2322  void x_PrintMessage(SDiagMessage::EEventType event,
2323  const string& message);
2324  // Start request or report error if one is already running
2325  static void x_StartRequest(void);
2326  // Log environment and registry variables as an extra message.
2327  static void x_LogEnvironment(void);
2328 
2330  friend class CDiagContext_Extra;
2331 
2332  // Reset logging rates to the values stored in CParam-s
2333  void ResetLogRates(void);
2334 
2335  // Check message logging rate
2336  bool ApproveMessage(SDiagMessage& msg, bool* show_warning);
2337 
2338  static void sx_ThreadDataTlsCleanup(CDiagContextThreadData* value,
2339  void* cleanup_data);
2341  friend class CDiagBuffer;
2342  friend class CRequestContext;
2343 
2344  // Default hit id initialization flags.
2346  eHitID_NoCreate, // Do not create new hit id.
2347  eHitID_Create // Create new hit id if it's not yet set.
2348  };
2349 
2350  // Check if current state is 'PB/P/PE'.
2351  bool x_DiagAtApplicationLevel(void) const;
2352  bool x_IsSetDefaultHitID(void) const;
2353  CSharedHitId x_GetDefaultHitID(EDefaultHitIDFlags flag) const;
2354  string x_GetNextHitID(bool is_default) const;
2355  void x_LogHitID(void) const;
2356  void x_LogHitID_WithLock(void) const; // Same as above but with mutex lock.
2357 
2358  // Saved messages to be flushed after setting up log files
2359  typedef list<SDiagMessage> TMessages;
2360 
2361  // Cached process ID
2362  static TPID sm_PID;
2363 
2364  mutable TUID m_UID;
2365  mutable unique_ptr<CEncodedString> m_Host;
2366  string m_HostIP;
2367  unique_ptr<CEncodedString> m_Username;
2368  unique_ptr<CEncodedString> m_AppName;
2369  mutable bool m_AppNameSet;
2370  mutable unique_ptr<CEncodedString> m_DefaultSessionId;
2371  mutable unique_ptr<CSharedHitId> m_DefaultHitId;
2372  mutable bool m_LoggedHitId;
2378  unique_ptr<CStopWatch> m_StopWatch;
2379  unique_ptr<TMessages> m_Messages;
2382 
2383  // Lock severity changes when using applog
2385 
2386  // Rate control
2387  unique_ptr<CRequestRateControl> m_AppLogRC;
2388  unique_ptr<CRequestRateControl> m_ErrLogRC;
2389  unique_ptr<CRequestRateControl> m_TraceLogRC;
2390  atomic<bool> m_AppLogSuspended;
2391  atomic<bool> m_ErrLogSuspended;
2392  atomic<bool> m_TraceLogSuspended;
2393 };
2394 
2395 
2396 /// Get diag context instance
2398 
2399 
2400 /////////////////////////////////////////////////////////////////////////////
2401 ///
2402 /// CNcbiLogFields --
2403 ///
2404 /// Automatic logging of application/request meta-data.
2405 
2407 {
2408 public:
2409  /// Load fields to be logged from NCBI_LOG_FIELDS environment variable.
2410  CNcbiLogFields(const string& source);
2411 
2412  ~CNcbiLogFields(void);
2413 
2414  /// Log (as an extra) all names/values matching fields in NCBI_LOG_FIELDS.
2415  /// If source passed to the constructor is not empty, all names are prefixed
2416  /// with 'source.' string.
2417  template<class TEntries>
2418  void LogFields(const TEntries& entries) const
2419  {
2421  for (typename TEntries::const_iterator it = entries.begin(); it != entries.end(); ++it) {
2422  x_Match(it->first, it->second, extra);
2423  }
2424  }
2425 
2426 private:
2427  // Check if the name matches any NCBI_LOG_FIELDS entry, print matching values to the extra.
2428  void x_Match(const string& name, const string& value, CDiagContext_Extra& extra) const;
2429 
2430  typedef list<string> TFields;
2431 
2432  string m_Source;
2434 };
2435 
2436 
2437 /////////////////////////////////////////////////////////////////////////////
2438 ///
2439 /// CDiagHandler --
2440 ///
2441 /// Base diagnostic handler class.
2442 
2443 /// Type of file for the output
2445 {
2446  eDiagFile_Err, ///< Error log file
2447  eDiagFile_Log, ///< Access log file
2448  eDiagFile_Trace, ///< Trace log file
2449  eDiagFile_Perf, ///< Perf log file
2450  eDiagFile_All ///< All log files
2451 };
2452 
2454 {
2455 public:
2456  /// Destructor.
2457  virtual ~CDiagHandler(void) {}
2458 
2459  /// Post message to handler.
2460  virtual void Post(const SDiagMessage& mess) = 0;
2461  /// Post message to console regardless of its severity.
2462  virtual void PostToConsole(const SDiagMessage& mess);
2463 
2464  /// Check if the handler supports async writes.
2465  /// @sa ComposeMessage, WriteMessage
2466  virtual bool AllowAsyncWrite(const SDiagMessage& msg) const;
2467  /// Compose message without writing it. If async mode is not
2468  /// supported, return empty string.
2469  virtual string ComposeMessage(const SDiagMessage& msg,
2470  EDiagFileType* file_type) const;
2471  /// Write string to the log. The string may contain multiple messages of
2472  /// the same type.
2473  virtual void WriteMessage(const char* buf,
2474  size_t len,
2476 
2477  /// Get current diag posts destination
2478  virtual string GetLogName(void);
2479 
2481  fTruncate = 0x01, ///< Truncate file to zero size
2482  fCheck = 0x02, ///< Reopen only if necessary
2483  fDefault = 0 ///< Default reopen flags:
2484  ///< - no truncation
2485  ///< - do not check if necessary
2486  };
2487  typedef int TReopenFlags;
2488 
2489  /// Reopen file to enable log rotation.
2490  virtual void Reopen(TReopenFlags /*flags*/) {}
2491 };
2492 
2493 
2494 /// Diagnostic handler function type.
2495 typedef void (*FDiagHandler)(const SDiagMessage& mess);
2496 
2497 /// Diagnostic cleanup function type.
2498 typedef void (*FDiagCleanup)(void* data);
2499 
2500 /// Set the diagnostic handler using the specified diagnostic handler class.
2502 extern void SetDiagHandler(CDiagHandler* handler,
2503  bool can_delete = true);
2504 
2505 /// Get the currently set diagnostic handler class.
2507 extern CDiagHandler* GetDiagHandler(bool take_ownership = false,
2508  bool* current_ownership = 0);
2509 
2510 /// Set the diagnostic handler using the specified diagnostic handler
2511 /// and cleanup functions.
2513 extern void SetDiagHandler(FDiagHandler func,
2514  void* data,
2516 
2517 /// Check if diagnostic handler is set.
2518 ///
2519 /// @return
2520 /// Return TRUE if user has ever set (or unset) diag. handler.
2522 extern bool IsSetDiagHandler(void);
2523 
2524 
2525 /// Ask diagnostic handler to reopen log files if necessary.
2527 extern void DiagHandler_Reopen(void);
2528 
2529 
2530 /////////////////////////////////////////////////////////////////////////////
2531 //
2532 // Diagnostic Filter Functionality
2533 //
2534 
2535 /// Diag severity types to put the filter on
2536 ///
2537 /// @sa SetDiagFilter
2539  eDiagFilter_Trace, ///< for TRACEs only
2540  eDiagFilter_Post, ///< for all non-TRACE, non-FATAL
2541  eDiagFilter_All ///< for all non-FATAL
2542 };
2543 
2544 
2545 /// Set diagnostic filter
2546 ///
2547 /// Diagnostic filter acts as a second level filtering mechanism
2548 /// (the primary established by global error post level)
2549 /// @param what
2550 /// Filter is set for
2551 /// @param filter_str
2552 /// Filter string
2553 /// @sa SetDiagPostLevel
2555 extern void SetDiagFilter(EDiagFilter what, const char* filter_str);
2556 
2557 /// Get current diagnostic filter
2558 ///
2559 /// @param what
2560 /// Filter is set for, only eDiagFilter_Trace and eDiagFilter_Post values are allowed,
2561 /// otherwise the function returns empty string.
2562 /// @sa SetDiagFilter
2564 extern string GetDiagFilter(EDiagFilter what);
2565 
2566 /// Append diagnostic filter
2567 ///
2568 /// @param what
2569 /// Filter is set for
2570 /// @param filter_str
2571 /// Filter string
2572 /// @sa SetDiagFilter
2574 extern void AppendDiagFilter(EDiagFilter what, const char* filter_str);
2575 
2576 
2577 /////////////////////////////////////////////////////////////////////////////
2578 ///
2579 /// CStreamDiagHandler_Base --
2580 ///
2581 /// Base class for stream and file based handlers
2582 
2584 {
2585 public:
2587 
2588  virtual string GetLogName(void);
2589  virtual CNcbiOstream* GetStream(void) { return 0; }
2590 
2591 protected:
2592  void SetLogName(const string& log_name);
2593 
2594 private:
2595  char m_LogName[2048];
2596 };
2597 
2598 
2599 /////////////////////////////////////////////////////////////////////////////
2600 ///
2601 /// CStreamDiagHandler --
2602 ///
2603 /// Specialization of "CDiagHandler" for the stream-based diagnostics.
2604 
2606 {
2607 public:
2608  /// Constructor.
2609  ///
2610  /// This does *not* own the stream; users will need to clean it up
2611  /// themselves if appropriate.
2612  /// @param os
2613  /// Output stream.
2614  /// @param quick_flush
2615  /// Do stream flush after every message.
2617  bool quick_flush = true,
2618  const string& stream_name = "");
2619 
2620  /// Post message to the handler.
2621  virtual void Post(const SDiagMessage& mess);
2622  virtual CNcbiOstream* GetStream(void) { return m_Stream; }
2623 
2624 protected:
2625  CNcbiOstream* m_Stream; ///< Diagnostic stream
2626 
2627 private:
2628  bool m_QuickFlush; ///< Quick flush of stream flag
2629 };
2630 
2631 
2632 class CDiagFileHandleHolder;
2633 
2634 /////////////////////////////////////////////////////////////////////////////
2635 ///
2636 /// CFileHandleDiagHandler --
2637 ///
2638 /// Specialization of "CDiagHandler" for the file-handle based diagnostics.
2639 /// Writes messages using system write rather than stream to make the
2640 /// operation really atomic. Re-opens file periodically to make rotation
2641 /// possible.
2642 
2644 {
2645 public:
2647 
2648  /// Constructor.
2649  ///
2650  /// Open file handle.
2651  /// themselves if appropriate.
2652  /// @param fname
2653  /// Output file name.
2654  /// @param file_type
2655  /// Type of log file.
2657  /// Close file handle
2658  ~CFileHandleDiagHandler(void);
2659 
2660  /// Post message to the handler.
2661  virtual void Post(const SDiagMessage& mess);
2662 
2663  virtual bool AllowAsyncWrite(const SDiagMessage& msg) const;
2664  virtual string ComposeMessage(const SDiagMessage& msg,
2665  EDiagFileType* file_type) const;
2666  virtual void WriteMessage(const char* buf,
2667  size_t len,
2669 
2670  bool Valid(void)
2671  {
2672  return (m_FileType == eDiagFile_Perf && !m_HavePosts)
2673  || m_Handle
2674  || m_LowDiskSpace;
2675  }
2676 
2677  // Reopen file to enable log rotation.
2678  virtual void Reopen(TReopenFlags flags);
2679 
2680 protected:
2681  virtual void SetLogName(const string& log_name);
2682 
2683 private:
2690 
2691  /// Save messages if the handle is unavailable
2692  typedef deque<SDiagMessage> TMessages;
2693  unique_ptr<TMessages> m_Messages;
2694 };
2695 
2696 
2697 /////////////////////////////////////////////////////////////////////////////
2698 ///
2699 /// CFileDiagHandler --
2700 ///
2701 /// Specialization of "CDiagHandler" for the file-based diagnostics.
2702 /// Splits output into three files: .err (severity higher than the
2703 /// threshold), .trace (severity below the threshold) and .log
2704 /// (application access log). Re-opens the files periodically
2705 /// to allow safe log rotation.
2706 
2708 {
2709 public:
2711 
2712  /// Constructor. initializes log file(s) with the arguments.
2713  /// @sa SetLogFile
2714  CFileDiagHandler(void);
2715  ~CFileDiagHandler(void);
2716 
2717  /// Post message to the handler. Info and Trace messages are sent
2718  /// to file_name.trace file, all others go to file_name.err file.
2719  /// Application access messages go to file_name.log file.
2720  virtual void Post(const SDiagMessage& mess);
2721 
2722  virtual bool AllowAsyncWrite(const SDiagMessage& msg) const;
2723  virtual string ComposeMessage(const SDiagMessage& msg,
2724  EDiagFileType* file_type) const;
2725  virtual void WriteMessage(const char* buf,
2726  size_t len,
2728 
2729  /// Set new log file.
2730  ///
2731  /// @param file_name
2732  /// File name. If file_type is eDiagFile_All, the output will be written
2733  /// to file_name.(err|log|trace). Otherwise the filename is used as-is.
2734  /// Special filenames are:
2735  /// "" - disable diag messages;
2736  /// "-" - print to stderr
2737  /// "/dev/null" - never add .(err|log|trace) to the name.
2738  /// @param file_type
2739  /// Type of log file to set - error, trace or application log.
2740  /// @param quick_flush
2741  /// Do stream flush after every message.
2742  bool SetLogFile(const string& file_name,
2744  bool quick_flush);
2745 
2746  /// Get current log file name. If file_type is eDiagFile_All, always
2747  /// returns empty string.
2748  string GetLogFile(EDiagFileType file_type) const;
2749 
2750  /// Get current log stream. Return NULL if the selected destination
2751  /// is not a stream.
2752  CNcbiOstream* GetLogStream(EDiagFileType file_type);
2753 
2754  // Reopen all files to enable log rotation.
2755  virtual void Reopen(TReopenFlags flags);
2756 
2757  // Set the selected sub-handler directly with the given ownership.
2758  void SetSubHandler(CStreamDiagHandler_Base* handler,
2760  bool own);
2761 
2762  /// Change ownership for the given handler if it's currently installed.
2763  void SetOwnership(CStreamDiagHandler_Base* handler, bool own);
2764 
2765 protected:
2766  virtual void SetLogName(const string& log_name);
2767 
2768 private:
2769  // Get file type for the message.
2770  EDiagFileType x_GetDiagFileType(const SDiagMessage& msg) const;
2771  // Get sub-handler for the given file type.
2772  CStreamDiagHandler_Base* x_GetHandler(EDiagFileType file_type) const;
2773 
2774  // Check if the object is owned and if it's used as more than one handler,
2775  // update ownership or delete the handler if necessary.
2776  void x_ResetHandler(CStreamDiagHandler_Base** ptr, bool* owned);
2777  // Set the selected member to the handler, make sure only one
2778  // ownership flag is set for the handler.
2779  void x_SetHandler(CStreamDiagHandler_Base** member,
2780  bool* own_member,
2782  bool own);
2783 
2785  bool m_OwnErr;
2787  bool m_OwnLog;
2793 };
2794 
2795 
2796 //////////////////////////////////////////////////////////////////////////
2797 /// CAsyncDiagHandler --
2798 ///
2799 /// Special handler that offloads physical printing of log messages to a
2800 /// separate thread. This handler should be installed into diagnostics
2801 /// only when it is completely initialized, i.e. no earlier than
2802 /// CNcbiApplication::Run() is called. Also it shouldn't be installed
2803 /// using standard SetDiagHandler() function, you have to use
2804 /// InstallToDiag() method of this handler. And don't forget to call
2805 /// RemoveFromDiag() before your application is finished.
2806 
2807 class CAsyncDiagThread;
2808 
2810 {
2811 public:
2812  CAsyncDiagHandler(void);
2813  virtual ~CAsyncDiagHandler(void);
2814 
2815  /// Install this DiagHandler into diagnostics.
2816  /// Method should be called only when diagnostics is completely
2817  /// initialized, i.e. no earlier than CNcbiApplication::Run() is called.
2818  /// Method can throw CThreadException if dedicated thread failed
2819  /// to start.
2820  void InstallToDiag(void);
2821  /// Remove this DiagHandler from diagnostics.
2822  /// This method must be called if InstallToDiag was called. Object cannot
2823  /// be destroyed if InstallToDiag was called and RemoveFromDiag wasn't
2824  /// called. If InstallToDiag wasn't called then this method does nothing
2825  /// and is safe to be executed.
2826  void RemoveFromDiag(void);
2827  /// Set custom suffix to use on all threads in the server's pool.
2828  /// Value can be set only before call to InstallToDiag(), any change
2829  /// of the value after call to InstallToDiag() will be ignored.
2830  void SetCustomThreadSuffix(const string& suffix);
2831 
2832  /// On the log queue overflow discard new log messages - instead of
2833  /// waiting for the queue to free up room for new messages.
2834  static void SetDiscardOnOverflow();
2835 
2836  /// Implementation of CDiagHandler
2837  virtual void Post(const SDiagMessage& mess);
2838  virtual string GetLogName(void);
2839  virtual void Reopen(TReopenFlags flags);
2840 
2841  size_t GetDroppedMessagesCount(void) const { return m_DroppedMessages.load(); }
2842  size_t GetDroppedRequestsCount(void) const { return m_DroppedRequests.load(); }
2843 
2844 private:
2845  /// Thread handling all physical printing of log messages
2848  bool m_DiscardOnOverflow = false;
2849  atomic<size_t> m_DroppedMessages;
2850  atomic<size_t> m_DroppedRequests;
2851 };
2852 
2853 
2854 /// Output diagnostics using both old and new style handlers.
2856 NCBI_XNCBI_EXPORT extern void SetDoubleDiagHandler(void); ///< @deprecated
2857 
2858 
2859 /// Set diagnostic stream.
2860 ///
2861 /// Error diagnostics are written to output stream "os".
2862 /// This uses the SetDiagHandler() functionality.
2864 extern void SetDiagStream
2865 (CNcbiOstream* os,
2866  bool quick_flush = true, ///< Do stream flush after every message
2867  FDiagCleanup cleanup = 0, ///< Call "cleanup(cleanup_data)" if diag.
2868  void* cleanup_data = 0, ///< Stream is changed (see SetDiagHandler)
2869  const string& stream_name = "" ///< Stream name (e.g. STDERR, file.log)
2870  );
2871 
2872 // Return TRUE if "os" is the current diag. stream.
2874 extern bool IsDiagStream(const CNcbiOstream* os);
2875 
2876 /// Get current diagnostic stream (if it was set by SetDiagStream) or NULL.
2878 extern CNcbiOstream* GetDiagStream(void);
2879 
2880 /// Split log files flag. If set, the output is sent to different
2881 /// log files depending on the severity level.
2882 NCBI_XNCBI_EXPORT extern void SetSplitLogFile(bool value = true);
2883 /// Get split log files flag.
2884 NCBI_XNCBI_EXPORT extern bool GetSplitLogFile(void);
2885 
2886 /// Set log files.
2887 /// Send output to file_name or to file_name.(err|log|trace) depending
2888 /// on the split log file flag and file_type. If a single file type
2889 /// is selected, other types remain the same or are switched to
2890 /// stderr if their files have not been assigned yet.
2891 /// If split log flag is off, any file type except eDiagFile_All
2892 /// will be ignored.
2893 /// If the file_name contains one of the extensions .log, .err or .trace
2894 /// and the file type is eDiagFile_All, the extension will be removed
2895 /// before adding the new one.
2896 /// Return true on success, false if the file could not be open.
2898 extern bool SetLogFile(const string& file_name,
2900  bool quick_flush = true);
2901 
2902 /// Get log file name for the given log type. Return empty string for
2903 /// eDiagFile_All or if the log file handler is not installed.
2905 extern string GetLogFile(EDiagFileType file_type);
2906 
2907 /// Get log file name or diag handler name.
2909 extern string GetLogFile(void);
2910 
2911 
2912 /// Use RW-lock for synchronization rather than mutex.
2913 /// NOTE:
2914 /// 1. The function should never be called when there are
2915 /// several threads running. Otherwise the result may
2916 /// be unpredictable. Also, do not call it from any diagnostic
2917 /// framework functions. E.g., it can not be called from
2918 /// CSomeDiagHandler::Post(). The best place to switch
2919 /// is in the very beginning of main().
2920 /// 2. In many cases switching to RW-lock will not improve
2921 /// the performance. E.g. any stream-based diag handlers including
2922 /// stderr will have to lock a mutex before writing a message anyway.
2923 /// Significant improvement may be seen only when using file handle
2924 /// based handlers which do atomic writes without additional locks.
2925 /// 3. If a custom diag handler is installed, it must take care
2926 /// about synchronization in Post() method. The framework only sets
2927 /// read lock before Post(), so it may be called from multiple
2928 /// threads at the same time.
2929 /// If in doubt, do not turn this on.
2930 /// The returned value is true on success, false if the switching
2931 /// fails for any reason.
2933 extern void g_Diag_Use_RWLock(bool enable = true);
2934 
2935 
2936 /////////////////////////////////////////////////////////////////////////////
2937 ///
2938 /// CDiagFactory --
2939 ///
2940 /// Diagnostic handler factory.
2941 
2943 {
2944 public:
2945  virtual ~CDiagFactory() { }
2946  /// Factory method interface.
2947  virtual CDiagHandler* New(const string& s) = 0;
2948 };
2949 
2950 
2951 
2952 /////////////////////////////////////////////////////////////////////////////
2953 ///
2954 /// CDiagRestorer --
2955 ///
2956 /// Auxiliary class to limit the duration of changes to diagnostic settings.
2957 
2959 {
2960 public:
2961  CDiagRestorer (void); ///< Captures current settings
2962  ~CDiagRestorer(void); ///< Restores captured settings
2963 private:
2964  /// Private new operator.
2965  ///
2966  /// Prohibit dynamic allocation because there's no good reason to allow
2967  /// it, and out-of-order destruction is problematic.
2968  void* operator new (size_t) { throw runtime_error("forbidden"); }
2969 
2970  /// Private new[] operator.
2971  ///
2972  /// Prohibit dynamic allocation because there's no good reason to allow
2973  /// it, and out-of-order destruction is problematic.
2974  void* operator new[] (size_t) { throw runtime_error("forbidden"); }
2975 
2976  /// Private delete operator.
2977  ///
2978  /// Prohibit dynamic deallocation (and allocation) because there's no
2979  /// good reason to allow it, and out-of-order destruction is problematic.
2980  void operator delete (void*) { }
2981 
2982  /// Private delete[] operator.
2983  ///
2984  /// Prohibit dynamic deallocation (and allocation) because there's no
2985  /// good reason to allow it, and out-of-order destruction is problematic.
2986  void operator delete[] (void*) { }
2987 
2988  string m_PostPrefix; ///< Message prefix
2989  list<string> m_PrefixList; ///< List of prefixes
2990  TDiagPostFlags m_PostFlags; ///< Post flags
2991  EDiagSev m_PostSeverity; ///< Post severity
2992  EDiagSevChange m_PostSeverityChange; ///< Severity change
2993  bool m_IgnoreToDie; ///< Ignore to die on die sev
2994  EDiagSev m_DieSeverity; ///< Die level severity
2995  EDiagTrace m_TraceDefault; ///< Default trace setting
2996  bool m_TraceEnabled; ///< Trace enabled?
2997  CDiagHandler* m_Handler; ///< Class handler
2998  bool m_CanDeleteHandler; ///< Can handler be deleted?
2999  CDiagErrCodeInfo* m_ErrCodeInfo; ///< Error code information
3000  bool m_CanDeleteErrCodeInfo; ///< Can delete err code info?
3001  bool m_ApplogSeverityLocked; ///< Limiting applog post level?
3002 };
3003 
3004 
3005 
3006 /////////////////////////////////////////////////////////////////////////////
3007 ///
3008 /// SDiagErrCodeDescription --
3009 ///
3010 /// Structure used to store the errors code and subcode description.
3011 
3013  /// Constructor.
3015 
3016  /// Destructor.
3017  SDiagErrCodeDescription(const string& message, ///< Message
3018  const string& explanation, ///< Explanation of msg.
3019  int severity = -1
3020  ///< Do not override
3021  ///< if set to -1
3022  )
3023  : m_Message(message),
3024  m_Explanation(explanation),
3025  m_Severity(severity)
3026  {
3027  return;
3028  }
3029 
3030 public:
3031  string m_Message; ///< Error message (short)
3032  string m_Explanation; ///< Error message (with detailed explanation)
3034  ///< Message severity (if less that 0, then use
3035  ///< current diagnostic severity level)
3036 };
3037 
3038 
3039 
3040 /////////////////////////////////////////////////////////////////////////////
3041 ///
3042 /// CDiagErrCodeInfo --
3043 ///
3044 /// Stores mapping of error codes and their descriptions.
3045 
3047 {
3048 public:
3049  /// Constructor.
3051 
3052  /// Constructor -- can throw runtime_error.
3053  CDiagErrCodeInfo(const string& file_name);
3054 
3055  /// Constructor -- can throw runtime_error.
3057 
3058  /// Destructor.
3060 
3061  /// Read error description from specified file.
3062  ///
3063  /// Read error descriptions from the specified file,
3064  /// store it in memory.
3065  bool Read(const string& file_name);
3066 
3067  /// Read error description from specified stream.
3068  ///
3069  /// Read error descriptions from the specified stream,
3070  /// store it in memory.
3071  bool Read(CNcbiIstream& is);
3072 
3073  /// Delete all stored error descriptions from memory.
3074  void Clear(void);
3075 
3076  /// Get description for specified error code.
3077  ///
3078  /// Get description message for the error by its code.
3079  /// @return
3080  /// TRUE if error description exists for this code;
3081  /// return FALSE otherwise.
3082  bool GetDescription(const ErrCode& err_code,
3083  SDiagErrCodeDescription* description) const;
3084 
3085  /// Set error description for specified error code.
3086  ///
3087  /// If description for this code already exist, then it
3088  /// will be overwritten.
3089  void SetDescription(const ErrCode& err_code,
3090  const SDiagErrCodeDescription& description);
3091 
3092  /// Check if error description exists.
3093  ///
3094  /// Return TRUE if description for specified error code exists,
3095  /// otherwise return FALSE.
3096  bool HaveDescription(const ErrCode& err_code) const;
3097 
3098 private:
3099 
3100  /// Define map for error messages.
3102 
3103  /// Map storing error codes and descriptions.
3105 };
3106 
3107 
3108 
3109 /// Diagnostic message file.
3110 #define DIAG_MESSAGE_FILE "MessageFile"
3111 
3112 /// Set handler for processing error codes.
3113 ///
3114 /// By default this handler is unset.
3115 /// NcbiApplication can init itself only if registry key DIAG_MESSAGE_FILE
3116 /// section DEBUG) is specified. The value of this key should be a name
3117 /// of the file with the error codes explanations.
3120  bool can_delete = true);
3121 
3122 /// Indicates whether an error-code processing handler has been set.
3124 extern bool IsSetDiagErrCodeInfo();
3125 
3126 /// Get handler for processing error codes.
3128 extern CDiagErrCodeInfo* GetDiagErrCodeInfo(bool take_ownership = false);
3129 
3130 
3131 /* @} */
3132 
3133 
3134 ///////////////////////////////////////////////////////
3135 // All inline function implementations and internal data
3136 // types, etc. are in this file
3137 
3138 #include <corelib/ncbidiag.inl>
3139 
3140 
3142 
3143 
3144 #endif /* CORELIB___NCBIDIAG__HPP */
CDiagAutoPrefix –.
Definition: ncbidiag.hpp:1428
Guard for collecting diag messages (affects the current thread only).
Definition: ncbidiag.hpp:1298
Incapsulate compile time information such as __FILE__, __LINE__, NCBI_MODULE, current function.
Definition: ncbidiag.hpp:65
Thread local context data stored in TLS.
Definition: ncbidiag.cpp:485
Temporary object for holding extra message arguments.
Definition: ncbidiag.hpp:1826
CDiagErrCodeInfo –.
Definition: ncbidiag.hpp:3047
CDiagFactory –.
Definition: ncbidiag.hpp:2943
CDiagRestorer –.
Definition: ncbidiag.hpp:2959
CEncodedString –.
Definition: ncbistr.hpp:4821
CFileDiagHandler –.
Definition: ncbidiag.hpp:2708
CFileHandleDiagHandler –.
Definition: ncbidiag.hpp:2644
CNcbiDiag –.
Definition: ncbidiag.hpp:922
CNcbiLogFields –.
Definition: ncbidiag.hpp:2407
CNcbiRegistry –.
Definition: ncbireg.hpp:921
CRequestRateControl –.
Helper class to hold hit id and sub-hit counter which can be shared between multiple request contexts...
Definition: request_ctx.hpp:66
CSpinLock –.
Definition: ncbimtx.hpp:843
CStopWatch –.
Definition: ncbitime.hpp:1936
CStreamDiagHandler_Base –.
Definition: ncbidiag.hpp:2584
CStreamDiagHandler –.
Definition: ncbidiag.hpp:2606
Template class for strict ID types.
Definition: ncbimisc.hpp:992
CTime –.
Definition: ncbitime.hpp:303
ErrCode –.
Definition: ncbidiag.hpp:813
Callback interface for stream parser.
Definition: ncbidiag.hpp:1573
MDiagClass –.
Definition: ncbidiag.hpp:881
MDiagFunction –.
Definition: ncbidiag.hpp:899
MDiagModule –.
Definition: ncbidiag.hpp:863
SetPostFlags –.
Definition: ncbidiag.hpp:846
Severity –.
Definition: ncbidiag.hpp:831
void(*)(CSeq_entry_Handle seh, IWorkbench *wb, const CSerialObject &obj) handler
void Print(const CCompactSAMApplication::AlignInfo &ai)
static uch flags
static ush * file_type
static const char ip[]
Definition: des.c:75
const char * file_name[]
static void cleanup(void)
Definition: ct_dynamic.c:30
CS_CONTEXT * ctx
Definition: t0006.c:12
#define true
Definition: bool.h:35
#define false
Definition: bool.h:36
static const char * str(char *buf, int n)
Definition: stats.c:84
char data[12]
Definition: iconv.c:80
#define NULL
Definition: ncbistd.hpp:225
int m_ErrCode
Error code.
Definition: ncbidiag.hpp:1657
int m_ErrSubCode
Sub Error code.
Definition: ncbidiag.hpp:1658
TFields m_Fields
Definition: ncbidiag.hpp:2433
int GetErrorSubCode(void) const
Get error subcode of the current message.
TDiagPostFlags GetPostFlags(void) const
Get post flags for the current message.
virtual CDiagHandler * New(const string &s)=0
Factory method interface.
string m_Explanation
Error message (with detailed explanation)
Definition: ncbidiag.hpp:3032
void Write(string &str, TDiagWriteFlags flags=fNone) const
Binary OR of "EDiagWriteFlags".
Definition: ncbidiag.cpp:5417
EFormatFlag m_Format
Definition: ncbidiag.hpp:1751
void SetDiagFilter(EDiagFilter what, const char *filter_str)
Set diagnostic filter.
Definition: ncbidiag.cpp:7784
TExtraArgs m_ExtraArgs
If event type is "extra", contains the list of arguments.
Definition: ncbidiag.hpp:1676
void PushDiagPostPrefix(const char *prefix)
Push a string to the list of message prefixes.
Definition: ncbidiag.cpp:6168
void Clear(void)
Delete all stored error descriptions from memory.
void ParseCurrFunctName(void) const
Definition: logging.cpp:1343
const char * GetModule(void) const
Get module name of the current message.
void SetDescription(const ErrCode &err_code, const SDiagErrCodeDescription &description)
Set error description for specified error code.
string m_PostPrefix
Message prefix.
Definition: ncbidiag.hpp:2988
TCount m_RequestId
FastCGI iteration or request ID.
Definition: ncbidiag.hpp:1667
EDiagPostFlag
Which parts of the diagnostic context should be posted.
Definition: ncbidiag.hpp:690
EDiagSev GetDiagPostLevel(void)
Get current threshold severity for posting the messages.
Definition: ncbidiag.cpp:6210
SetPostFlags(TDiagPostFlags flags)
Definition: ncbidiag.hpp:848
void SetDiagPostFlag(EDiagPostFlag flag)
Set the specified flag (globally).
Definition: ncbidiag.cpp:6129
static const char * kProperty_UserName
Global properties.
Definition: ncbidiag.hpp:2050
EDiagSevChange
Severity level change state.
Definition: ncbidiag.hpp:664
EDiagSev m_SeverityCap
Definition: ncbidiag.hpp:1381
friend const CNcbiDiag & Message(const CNcbiDiag &diag)
Set IsMessage flag to indicate that the current post is a message.
bool m_AllowBadExtraNames
Definition: ncbidiag.hpp:1756
unique_ptr< CEncodedString > m_Username
Definition: ncbidiag.hpp:2367
int m_Code
Major error code number.
Definition: ncbidiag.hpp:819
TDiagPostFlags m_PostFlags
Bitwise OR of "EDiagPostFlag".
Definition: ncbidiag.hpp:1209
static TPID sm_PID
Definition: ncbidiag.hpp:2362
CStreamDiagHandler_Base * m_Perf
Definition: ncbidiag.hpp:2790
string m_StrCurrFunctName
Definition: ncbidiag.hpp:122
const char * m_File
File name.
Definition: ncbidiag.hpp:1652
EDiagSev m_PostSeverity
Post severity.
Definition: ncbidiag.hpp:2991
Uint8 TCount
Generic type for counters (posts, requests etc.)
Definition: ncbidiag.hpp:1603
TTID m_TID
Thread ID.
Definition: ncbidiag.hpp:1664
const char * m_Buffer
Not guaranteed to be '\0'-terminated!
Definition: ncbidiag.hpp:1650
void SetModule(const string &module)
Definition: ncbidiag.cpp:767
CStreamDiagHandler_Base * m_Trace
Definition: ncbidiag.hpp:2788
const CNcbiDiag & SetClass(const char *nclass) const
Set class name.
Definition: ncbidiag.cpp:7874
CNcbiOstream * m_Stream
Diagnostic stream.
Definition: ncbidiag.hpp:2625
EDiagSev m_CollectSev
Definition: ncbidiag.hpp:1380
CDiagErrCodeInfo(void)
Constructor.
void SetLine(int line)
Definition: ncbidiag.cpp:774
CDiagContext & GetDiagContext(void)
Get diag context instance.
Definition: logging.cpp:820
void(* FAbortHandler)(void)
Abort handler function type.
Definition: ncbidiag.hpp:1522
CDiagErrCodeInfo(CNcbiIstream &is)
Constructor – can throw runtime_error.
bool HaveDescription(const ErrCode &err_code) const
Check if error description exists.
EDiagSev m_Severity
Severity level of current msg.
Definition: ncbidiag.hpp:1205
map< string, string > TProperties
Definition: ncbidiag.hpp:2329
const CNcbiDiag &(* FManip)(const CNcbiDiag &)
Diagnostic stream manipulator.
Definition: ncbidiag.hpp:952
const char * m_Module
Definition: ncbidiag.hpp:110
void SetDiagFixedPostLevel(EDiagSev post_sev)
Sets and locks the level, combining the previous two calls.
Definition: ncbidiag.cpp:6238
void SetAction(EAction action)
Specify on-destroy action.
Definition: ncbidiag.hpp:1360
Uint8 GetStartingPoint(void) const
Get the lowest thread-local post number in this guard's scope.
Definition: ncbidiag.hpp:1363
void SetSplitLogFile(bool value=true)
Split log files flag.
Definition: ncbidiag.cpp:6764
EDiagCollectMessages
Flags to control collecting messages and flushing them to the new destination when switching diag han...
Definition: ncbidiag.hpp:1796
TExtraArgs * m_Args
Definition: ncbidiag.hpp:1917
list< string > TFields
Definition: ncbidiag.hpp:2430
const char * m_Module
Module name.
Definition: ncbidiag.hpp:1653
static const char * kProperty_AppName
Definition: ncbidiag.hpp:2053
static const char * kProperty_ClientIP
Definition: ncbidiag.hpp:2058
MDiagClass(const char *nclass)
void SetAllPostFlags(TDiagPostFlags flags) const
Set new post flags for the current message.
static bool sm_ApplogSeverityLocked
Definition: ncbidiag.hpp:2384
size_t m_MaxMessages
Definition: ncbidiag.hpp:2380
bool m_TraceEnabled
Trace enabled?
Definition: ncbidiag.hpp:2996
void DiagHandler_Reopen(void)
Ask diagnostic handler to reopen log files if necessary.
Definition: ncbidiag.cpp:6403
string GetDiagFilter(EDiagFilter what)
Get current diagnostic filter.
Definition: ncbidiag.cpp:7795
friend const CNcbiDiag & StackTrace(const CNcbiDiag &diag)
Print stack trace.
int GetExitSignal(void) const
Get exit signal.
Definition: ncbidiag.hpp:2181
virtual void Reopen(TReopenFlags)
Reopen file to enable log rotation.
Definition: ncbidiag.hpp:2490
unique_ptr< CRequestRateControl > m_TraceLogRC
Definition: ncbidiag.hpp:2389
const CNcbiDiag & Put(const FManip, const FManip &manip) const
Helper method to handle various diagnostic stream manipulators.
Definition: ncbidiag.hpp:1009
CAsyncDiagThread * m_AsyncThread
Thread handling all physical printing of log messages.
Definition: ncbidiag.hpp:2846
atomic< bool > m_ErrLogSuspended
Definition: ncbidiag.hpp:2391
const char * m_Class
Definition: ncbidiag.hpp:887
CDiagContext_Extra Extra(void) const
Create a temporary CDiagContext_Extra object.
Definition: ncbidiag.hpp:2093
void CheckErrSubcodeX(int)
Additional dummy function for use in NCBI_CHECK_ERR_SUBCODE_X macro.
Definition: ncbidiag.hpp:440
friend const CNcbiDiag & Fatal(const CNcbiDiag &diag)
Flush current message, then set a severity for the next diagnostic message to FATAL.
list< SDiagMessage > TMessages
Definition: ncbidiag.hpp:2359
TCount m_ProcPost
Number of the post in the process.
Definition: ncbidiag.hpp:1665
const CNcbiDiag & SetLine(size_t line) const
Set line number for post.
bool DisableDiagPostLevelChange(bool disable_change=true)
Disable change the diagnostic post level.
Definition: ncbidiag.cpp:6245
bool IsCollectingMessages(void) const
Check if message collecting is on.
Definition: ncbidiag.hpp:2241
CDiagErrCodeInfo(const string &file_name)
Constructor – can throw runtime_error.
int GetErrorCode(void) const
Get error code of the current message.
friend const CNcbiDiag & Console(const CNcbiDiag &diag)
Set IsConsole flag to indicate that the current post should go to console regardless of its severity ...
bool IsSetExitCode(void) const
Check if exit code has been set.
Definition: ncbidiag.hpp:2170
string m_StrModule
Definition: ncbidiag.hpp:121
virtual ~CDiagFactory()
Definition: ncbidiag.hpp:2945
int m_ErrSubCode
Error subcode.
Definition: ncbidiag.hpp:1207
const CNcbiDiag & SetErrorCode(int code=0, int subcode=0) const
Set error code and subcode numbers.
Uint8 TPID
Process ID.
Definition: ncbidiag.hpp:1598
size_t m_Line
Line number in file.
Definition: ncbidiag.hpp:1656
CNcbiDiag(const CNcbiDiag &)
Private copy constructor to prohibit copy.
void SetDiagRequestId(Uint8 id)
Set iteration number/request ID.
Definition: ncbidiag.cpp:1241
CDiagBuffer & m_Buffer
This thread's error msg. buffer.
Definition: ncbidiag.hpp:1208
static const char * kProperty_ExitSig
Definition: ncbidiag.hpp:2054
bool CheckFilters(const CException *ex=NULL) const
Check if filters are passed for the current message.
Definition: ncbidiag.cpp:7888
bool m_AppNameSet
Definition: ncbidiag.hpp:2369
~CDiagCompileInfo(void)
Definition: logging.cpp:1336
friend const CNcbiDiag & Info(const CNcbiDiag &diag)
Flush current message, then set a severity for the next diagnostic message to INFO.
bool m_CanDeleteErrCodeInfo
Can delete err code info?
Definition: ncbidiag.hpp:3000
const CNcbiDiag & Put(const CException *, const X &x) const
Helper method to post an exception to diagnostic stream.
Definition: ncbidiag.hpp:973
atomic< size_t > m_DroppedMessages
Definition: ncbidiag.hpp:2849
int TDiagPostFlags
Binary OR of "EDiagPostFlag".
Definition: ncbidiag.hpp:783
EDiagSev m_Severity
Severity level.
Definition: ncbidiag.hpp:1649
const string & GetClass(void) const
bool GetSplitLogFile(void)
Get split log files flag.
Definition: ncbidiag.cpp:6770
virtual void operator()(SDiagMessage &msg)=0
~CNcbiDiag(void)
Destructor.
Definition: ncbidiag.cpp:7846
bool m_QuickFlush
Quick flush of stream flag.
Definition: ncbidiag.hpp:2628
unique_ptr< TMessages > m_Messages
Definition: ncbidiag.hpp:2693
const CNcbiDiag & Put(const exception *, const X &x) const
Definition: ncbidiag.hpp:978
bool GetOmitStackTrace(void) const
Definition: ncbidiag.hpp:1197
friend const CNcbiDiag & Note(const CNcbiDiag &diag)
Set IsNote flag to indicate that the current post is a note.
void SetSeverityCap(EDiagSev sev)
Set new severity cap for use in PrintCapped mode.
Definition: ncbidiag.hpp:1355
EDiagWriteFlags
Compose a message string in the standard format(see also "flags"): "<file>", line <line>: <severity>:...
Definition: ncbidiag.hpp:1700
unique_ptr< CEncodedString > m_Host
Definition: ncbidiag.hpp:2365
CNcbiIos &(* FIosManip)(CNcbiIos &)
Definition: ncbidiag.hpp:954
EAppDiagStream
Where to write the application's diagnostics to.
Definition: ncbidiag.hpp:1778
EDiagTrace m_TraceDefault
Default trace setting.
Definition: ncbidiag.hpp:2995
Uint8 TTID
Get thread ID used in messages.
Definition: ncbidiag.hpp:2270
void UnsetDiagTraceFlag(EDiagPostFlag flag)
Definition: ncbidiag.cpp:6150
EPostNumberIncrement
Post number increment flag for GetProcessPostNumber() and GetThreadPostNumber().
Definition: ncbidiag.hpp:1809
const char * m_Prefix
Prefix string.
Definition: ncbidiag.hpp:1660
const char * GetFile(void) const
virtual void Post(const SDiagMessage &mess)=0
Post message to handler.
friend const CNcbiDiag & operator<<(const CNcbiDiag &diag, const MDiagFunction &function)
EDiagSev GetDiagDieLevel(void)
Get the "die" (abort) level for the program.
Definition: ncbidiag.cpp:6270
const CNcbiDiag & GetRef(void) const
Some compilers (e.g.
Definition: ncbidiag.hpp:944
string m_Message
Error message (short)
Definition: ncbidiag.hpp:3031
const CNcbiDiag & Put(const ErrCode *, const ErrCode &err_code) const
Helper method to post error code and subcode to diagnostic stream.
const CNcbiDiag & operator<<(FManip manip) const
Definition: ncbidiag.hpp:1013
virtual ~INextDiagMessage(void)
Definition: ncbidiag.hpp:1576
bool IsDiagStream(const CNcbiOstream *os)
Definition: ncbidiag.cpp:7750
size_t GetLine(void) const
Get line number for the current message.
TProperties m_Properties
Definition: ncbidiag.hpp:2377
bool IsVisibleDiagPostLevel(EDiagSev sev)
Check if the specified severity is higher or equal to the currently selected post level and will be p...
Definition: ncbidiag.cpp:6225
EEventType
Type of event to report.
Definition: ncbidiag.hpp:1638
TDiagPostFlags m_Flags
Bitwise OR of "EDiagPostFlag".
Definition: ncbidiag.hpp:1659
SDiagErrCodeDescription(const string &message, const string &explanation, int severity=-1)
Destructor.
Definition: ncbidiag.hpp:3017
bool m_NoTee
Special flag indicating that the message should not be printed by Tee-handler.
Definition: ncbidiag.hpp:1683
static CDiagContext * sm_Instance
Definition: ncbidiag.hpp:2381
EDiagSev m_DieSeverity
Die level severity.
Definition: ncbidiag.hpp:2994
const CNcbiDiag & Put(const Severity *, const Severity &severity) const
Helper method to set severity level.
map< ErrCode, SDiagErrCodeDescription > TInfo
Define map for error messages.
Definition: ncbidiag.hpp:3101
atomic< bool > m_AppLogSuspended
Definition: ncbidiag.hpp:2390
void PopDiagPostPrefix(void)
Pop a string from the list of message prefixes.
Definition: ncbidiag.cpp:6178
EDiagAppState m_AppState
Definition: ncbidiag.hpp:2376
void AppendDiagFilter(EDiagFilter what, const char *filter_str)
Append diagnostic filter.
Definition: ncbidiag.cpp:7808
static void DiagTrouble(const CDiagCompileInfo &info, const char *message=NULL)
Display trouble error message.
Definition: ncbidiag.cpp:8052
MDiagModule(const char *module)
static const char * kProperty_ReqTime
Definition: ncbidiag.hpp:2061
bool GetDiagTrace(void)
Check if traces are enabled.
Definition: ncbidiag.cpp:6299
void SetFastCGIIteration(Uint8 id)
Definition: ncbidiag.hpp:1415
CStopWatch * m_ReopenTimer
Definition: ncbidiag.hpp:2689
static void SetApplogSeverityLocked(bool lock)
Definition: ncbidiag.hpp:2296
const CNcbiDiag & SetFile(const char *file) const
Set file name to post.
Definition: ncbidiag.cpp:7860
CNcbiDiag(EDiagSev sev=eDiag_Error, TDiagPostFlags post_flags=eDPF_Default)
Constructor.
Definition: ncbidiag.cpp:7823
CStopWatch * m_ReopenTimer
Definition: ncbidiag.hpp:2792
CStreamDiagHandler_Base * m_Log
Definition: ncbidiag.hpp:2786
const string & GetHostIP(void) const
Get host IP address.
Definition: ncbidiag.hpp:2158
TCount m_ThrPost
Number of the post in the thread.
Definition: ncbidiag.hpp:1666
friend const CNcbiDiag & Trace(const CNcbiDiag &diag)
Flush current message, then set a severity for the next diagnostic message to TRACE.
EDiagSevChange m_PostSeverityChange
Severity change.
Definition: ncbidiag.hpp:2992
int m_Severity
Message severity (if less that 0, then use current diagnostic severity level)
Definition: ncbidiag.hpp:3033
int CompareDiagPostLevel(EDiagSev sev1, EDiagSev sev2)
Compare two severities.
Definition: ncbidiag.cpp:6216
static const char * kProperty_ExitCode
Definition: ncbidiag.hpp:2055
void UnsetDiagPostFlag(EDiagPostFlag flag)
Unset the specified flag (globally).
Definition: ncbidiag.cpp:6134
const char * m_Module
Definition: ncbidiag.hpp:869
unique_ptr< CStopWatch > m_StopWatch
Definition: ncbidiag.hpp:2378
CDiagHandler * GetDiagHandler(bool take_ownership=false, bool *current_ownership=0)
Get the currently set diagnostic handler class.
Definition: ncbidiag.cpp:6388
void SetDiagPostPrefix(const char *prefix)
Specify a string to prefix all subsequent error postings with.
Definition: ncbidiag.cpp:6156
void ResetIsConsoleFlag(void) const
Reset IsConsole flag.
Definition: ncbidiag.hpp:1195
void SetDoubleDiagHandler(void)
Output diagnostics using both old and new style handlers.
Definition: ncbidiag.cpp:8243
int TDiagWriteFlags
Definition: ncbidiag.hpp:1706
bool m_OmitStackTrace
Definition: ncbidiag.hpp:1210
EDiagSev SetDiagDieLevel(EDiagSev die_sev=eDiag_Fatal)
Set the "die" (abort) level for the program.
Definition: ncbidiag.cpp:6255
const char * m_Function
Definition: ncbidiag.hpp:905
EDiagFileType m_FileType
Definition: ncbidiag.hpp:2684
NCBI_XNCBI_EXPORT void Abort(void)
Smart abort function.
Definition: ncbidiag.cpp:8261
IOS_BASE &(* FIosbaseManip)(IOS_BASE &)
Definition: ncbidiag.hpp:953
void x_EndMess(void) const
Private replacement for Endm called from manipulators.
const CNcbiDiag & SetFunction(const char *function) const
Set function name.
Definition: ncbidiag.cpp:7881
static void DiagValidate(const CDiagCompileInfo &info, const char *expression, const char *message)
Display validation message.
Definition: ncbidiag.cpp:8079
list< TExtraArg > TExtraArgs
Definition: ncbidiag.hpp:1673
size_t m_BufferLen
Length of m_Buffer.
Definition: ncbidiag.hpp:1651
static const char * kProperty_HostName
Definition: ncbidiag.hpp:2051
void SetDiagErrCodeInfo(CDiagErrCodeInfo *info, bool can_delete=true)
Set handler for processing error codes.
Definition: ncbidiag.cpp:7758
static void DiagAssertIfSuppressedSystemMessageBox(const CDiagCompileInfo &info, const char *expression, const char *message=NULL)
Same as DiagAssert but only if the system message box is suppressed.
Definition: ncbidiag.cpp:8069
static TDiagPostFlags ForceImportantFlags(TDiagPostFlags flags)
Set important flags to their globally set values.
Definition: ncbidiag.cpp:7851
TDiagPostFlags SetPostFlags(TDiagPostFlags flags) const
Set specific post flags for the current message.
static const char * SeverityName(EDiagSev sev)
Get a common symbolic name for the severity levels.
EDiagSev m_PrintSev
Definition: ncbidiag.hpp:1379
EDiagSev SetDiagPostLevel(EDiagSev post_sev=eDiag_Error)
Set the threshold severity for posting the messages.
Definition: ncbidiag.cpp:6188
EDiagTrace
Which setting disables/enables posting of "eDiag_Trace" messages.
Definition: ncbidiag.hpp:1545
EAction
Action to perform in guard's destructor.
Definition: ncbidiag.hpp:1301
ELogRate_Type
Type of logging rate limit.
Definition: ncbidiag.hpp:2274
void SetExitCode(int exit_code)
Set exit code.
Definition: ncbidiag.hpp:2174
CDiagFileHandleHolder * m_Handle
Definition: ncbidiag.hpp:2687
friend const CNcbiDiag & Reset(const CNcbiDiag &diag)
Reset the content of current message.
bool m_LoggedHitId
Definition: ncbidiag.hpp:2372
friend const CNcbiDiag & Critical(const CNcbiDiag &diag)
Flush current message, then set a severity for the next diagnostic message to CRITICAL ERROR.
FOnForkAction
Actions to perform in UpdateOnFork().
Definition: ncbidiag.hpp:1942
const char * m_File
Definition: ncbidiag.hpp:109
void SetOmitStackTrace(bool value)
Definition: ncbidiag.hpp:1198
friend const CNcbiDiag & Warning(const CNcbiDiag &diag)
Flush current message, then set a severity for the next diagnostic message to WARNING.
void(* FDiagHandler)(const SDiagMessage &mess)
Diagnostic handler function type.
Definition: ncbidiag.hpp:2495
void SetExitSignal(int exit_sig)
Set exit signal.
Definition: ncbidiag.hpp:2183
SDiagMessage::EEventType m_EventType
Definition: ncbidiag.hpp:1916
const char * m_Class
Class name.
Definition: ncbidiag.hpp:1654
deque< SDiagMessage > TMessages
Save messages if the handle is unavailable.
Definition: ncbidiag.hpp:2692
int m_ErrCode
Error code.
Definition: ncbidiag.hpp:1206
EDiagSev GetSeverityCap(void) const
Get current severity cap for use in ePrintCapped mode.
Definition: ncbidiag.hpp:1353
~CDiagErrCodeInfo(void)
Destructor.
string m_HostIP
Definition: ncbidiag.hpp:2366
TDiagPostFlags m_PostFlags
Post flags.
Definition: ncbidiag.hpp:2990
CStreamDiagHandler_Base TParent
Definition: ncbidiag.hpp:2646
Severity(EDiagSev sev)
Definition: ncbidiag.hpp:833
pair< string, string > TExtraArg
Definition: ncbidiag.hpp:1672
static NCBI_XNCBI_EXPORT void DiagAssert(const CDiagCompileInfo &info, const char *expression, const char *message=NULL)
Assert specified expression and report results.
Definition: ncbidiag.cpp:8058
EDisabledAppLogEvents
Flags for disabling groups of applog events with DIAG_DISABLE_APPLOG_MESSAGES.
Definition: ncbidiag.hpp:2306
static const char * kProperty_BytesRd
Definition: ncbidiag.hpp:2062
string m_FunctName
Definition: ncbidiag.hpp:117
EDiagSev GetCollectSeverity(void) const
Get current collect severity.
Definition: ncbidiag.hpp:1347
SDiagMessage::TCount TCount
Definition: ncbidiag.hpp:2263
bool IsSetDiagPostFlag(EDiagPostFlag flag, TDiagPostFlags flags=eDPF_Default)
Check if a specified flag is set.
TInfo m_Info
Map storing error codes and descriptions.
Definition: ncbidiag.hpp:3104
void x_SetFormat(EFormatFlag fmt) const
Definition: ncbidiag.hpp:1741
const char * GetFunction(void) const
Get function name of the current message.
const CNcbiDiag & Put(const volatile void *, const X &x) const
Generic method to post to diagnostic stream.
virtual CNcbiOstream * GetStream(void)
Definition: ncbidiag.hpp:2622
CSpinLock * m_HandleLock
Definition: ncbidiag.hpp:2688
TDiagPostFlags m_Flags
flags to set
Definition: ncbidiag.hpp:850
EDiagFileType
CDiagHandler –.
Definition: ncbidiag.hpp:2445
EDiagAppState
Application execution states shown in the std prefix.
Definition: ncbidiag.hpp:787
friend const CNcbiDiag & Endm(const CNcbiDiag &diag)
Flush current message, start new one.
string m_ClassName
Definition: ncbidiag.hpp:116
friend const CNcbiDiag & Error(const CNcbiDiag &diag)
Flush current message, then set a severity for the next diagnostic message to ERROR.
void(* FDiagCleanup)(void *data)
Diagnostic cleanup function type.
Definition: ncbidiag.hpp:2498
CDiagCompileInfo m_CompileInfo
Definition: ncbidiag.hpp:1212
list< string > m_PrefixList
List of prefixes.
Definition: ncbidiag.hpp:2989
const CNcbiDiag & Put(const ncbi::SetPostFlags *, const ncbi::SetPostFlags &flags) const
Helper method to set specific post flags.
CStreamDiagHandler_Base * m_Err
Definition: ncbidiag.hpp:2784
bool m_ApplogSeverityLocked
Limiting applog post level?
Definition: ncbidiag.hpp:3001
Uint8 TTID
Thread ID.
Definition: ncbidiag.hpp:1599
TDiagPostFlags SetDiagTraceAllFlags(TDiagPostFlags flags)
Versions of the above for extra trace flags.
Definition: ncbidiag.cpp:6140
const CNcbiDiag & x_Put(const CException &ex) const
Helper func for the exception-related Put()
Definition: ncbidiag.cpp:7931
bool SetLogFile(const string &file_name, EDiagFileType file_type=eDiagFile_All, bool quick_flush=true)
Set log files.
Definition: ncbidiag.cpp:7642
static const char * kProperty_SessionID
Definition: ncbidiag.hpp:2059
bool IsSetDiagHandler(void)
Check if diagnostic handler is set.
Definition: ncbidiag.cpp:6383
virtual ~CDiagHandler(void)
Destructor.
Definition: ncbidiag.hpp:2457
void ResetIsMessageFlag(void) const
Definition: ncbidiag.hpp:1189
unique_ptr< CSharedHitId > m_DefaultHitId
Definition: ncbidiag.hpp:2371
const char * m_Function
Function name.
Definition: ncbidiag.hpp:1655
CNcbiOstream & operator<<(CNcbiOstream &os, const SDiagMessage &mess)
Insert message in output stream.
Definition: ncbidiag.hpp:1760
atomic< size_t > m_DroppedRequests
Definition: ncbidiag.hpp:2850
void LogFields(const TEntries &entries) const
Log (as an extra) all names/values matching fields in NCBI_LOG_FIELDS.
Definition: ncbidiag.hpp:2418
void SetDiagHandler(CDiagHandler *handler, bool can_delete=true)
Set the diagnostic handler using the specified diagnostic handler class.
Definition: ncbidiag.cpp:6347
ErrCode(int code, int subcode=0)
Constructor.
Definition: ncbidiag.hpp:816
string GetGlobalRequestId(void) const
Deprecated version of HID generator.
Definition: ncbidiag.hpp:1995
TPID m_PID
Process ID.
Definition: ncbidiag.hpp:1663
const string & GetFunction(void) const
SDiagMessage::TExtraArgs TExtraArgs
Definition: ncbidiag.hpp:1862
const char * m_ErrText
Sometimes 'error' has no numeric code, but can be represented as text.
Definition: ncbidiag.hpp:1661
atomic< bool > m_TraceLogSuspended
Definition: ncbidiag.hpp:2392
void SetDiagTrace(EDiagTrace how, EDiagTrace dflt=eDT_Default)
Set the diagnostic trace settings.
Definition: ncbidiag.cpp:6285
const char * GetClass(void) const
Get class name of the current message.
CDiagHandler * m_Handler
Class handler.
Definition: ncbidiag.hpp:2997
EDiagSev
Severity level for the posted diagnostics.
Definition: ncbidiag.hpp:648
const char * g_DiagUnknownFunction(void)
Definition: ncbidiag.cpp:8455
EEventType m_Event
If eDPF_AppLog flag is set, m_Event contains event type.
Definition: ncbidiag.hpp:1670
TDiagPostFlags SetDiagPostAllFlags(TDiagPostFlags flags)
Set global post flags to "flags".
Definition: ncbidiag.cpp:6124
bool x_NeedModule(void) const
Definition: ncbidiag.cpp:735
void SetFunction(const string &func)
Definition: ncbidiag.cpp:780
Uint8 GetDiagRequestId(void)
Get iteration number/request ID.
Definition: ncbidiag.cpp:1235
const char * GetFile(void) const
Get file used for the current message.
bool m_IgnoreToDie
Ignore to die on die sev.
Definition: ncbidiag.hpp:2993
MDiagFunction(const char *function)
Uint8 GetFastCGIIteration(void)
Definition: ncbidiag.hpp:1408
SDiagMessage::TExtraArg TExtraArg
Definition: ncbidiag.hpp:1861
CNcbiOstream * GetDiagStream(void)
Get current diagnostic stream (if it was set by SetDiagStream) or NULL.
Definition: ncbidiag.cpp:8222
unique_ptr< TMessages > m_Messages
Definition: ncbidiag.hpp:2379
static NCBI_XNCBI_EXPORT void DiagFatal(const CDiagCompileInfo &info, const char *message)
Display fatal error message.
Definition: ncbidiag.cpp:8043
bool IsSetDiagErrCodeInfo()
Indicates whether an error-code processing handler has been set.
Definition: ncbidiag.cpp:7768
CDiagErrCodeInfo * m_ErrCodeInfo
Error code information.
Definition: ncbidiag.hpp:2999
unique_ptr< CRequestRateControl > m_AppLogRC
Definition: ncbidiag.hpp:2387
static const char * kProperty_HostIP
Definition: ncbidiag.hpp:2052
const char * m_CurrFunctName
Definition: ncbidiag.hpp:113
int GetLine(void) const
size_t GetDroppedMessagesCount(void) const
Definition: ncbidiag.hpp:2841
static bool StrToSeverityLevel(const char *str_sev, EDiagSev &sev)
Get severity from string.
Definition: ncbidiag.cpp:8018
EPropertyMode
Property visibility flag.
Definition: ncbidiag.hpp:2012
EDiagSev GetPrintSeverity(void) const
Get current print severity.
Definition: ncbidiag.hpp:1341
static const char * kProperty_AppState
Per-thread properties.
Definition: ncbidiag.hpp:2057
int GetExitCode(void) const
Get exit code.
Definition: ncbidiag.hpp:2172
CDiagContext(const CDiagContext &)
Int8 TUID
Unique process ID.
Definition: ncbidiag.hpp:1600
void SetFile(const string &file)
Definition: ncbidiag.cpp:760
void SetClass(const string &cls)
Definition: ncbidiag.cpp:795
void SetDiagTraceFlag(EDiagPostFlag flag)
Definition: ncbidiag.cpp:6145
EDiagSev m_Level
Severity level.
Definition: ncbidiag.hpp:835
CDiagContext & operator=(const CDiagContext &)
CDiagErrCodeInfo * GetDiagErrCodeInfo(bool take_ownership=false)
Get handler for processing error codes.
Definition: ncbidiag.cpp:7773
CStreamDiagHandler_Base TParent
Definition: ncbidiag.hpp:2710
friend const CNcbiDiag & operator<<(const CNcbiDiag &diag, const MDiagModule &module)
bool m_PrintStackTrace
Definition: ncbidiag.hpp:1685
TDiagPostFlags ResetPostFlags(TDiagPostFlags flags) const
Clear specific post flags for the current message.
bool m_ExitCodeSet
Definition: ncbidiag.hpp:2374
static bool IsApplogSeverityLocked(void)
When using applog, the diag post level is locked to Warning.
Definition: ncbidiag.hpp:2294
unique_ptr< CEncodedString > m_DefaultSessionId
Definition: ncbidiag.hpp:2370
string GetLogFile(EDiagFileType file_type)
Get log file name for the given log type.
Definition: ncbidiag.cpp:7726
static const char * kProperty_BytesWr
Definition: ncbidiag.hpp:2063
void SetDiagStream(CNcbiOstream *os, bool quick_flush=true, FDiagCleanup cleanup=0, void *cleanup_data=0, const string &stream_name="")
Set diagnostic stream.
Definition: ncbidiag.cpp:8197
unique_ptr< CEncodedString > m_AppName
Definition: ncbidiag.hpp:2368
void SetAbortHandler(FAbortHandler func=0)
Set/unset abort handler.
Definition: ncbidiag.cpp:8255
void x_LogHitID(bool ignore_app_state=false) const
int m_SubCode
Minor error code number.
Definition: ncbidiag.hpp:820
CDiagCompileInfo(void)
CDiagCompileInfo::
Definition: logging.cpp:1288
friend const CNcbiDiag & operator<<(const CNcbiDiag &diag, const MDiagClass &nclass)
void ResetIsNoteFlag(void) const
Reset IsNote flag.
Definition: ncbidiag.hpp:1192
EDiagFilter
Diag severity types to put the filter on.
Definition: ncbidiag.hpp:2538
EDiagSev GetSeverity(void) const
Get severity of the current message.
EAction GetAction(void) const
Get selected on-destroy action.
Definition: ncbidiag.hpp:1358
bool m_TypedExtra
Set to true if this is a typed extra message (the arguments include "NCBIEXTRATYPE=<extra-type>").
Definition: ncbidiag.hpp:1679
CNcbiDiag & operator=(const CNcbiDiag &)
Private assignment operator to prohibit assignment.
static const char * kProperty_ReqStatus
Definition: ncbidiag.hpp:2060
void g_Diag_Use_RWLock(bool enable=true)
Use RW-lock for synchronization rather than mutex.
Definition: ncbidiag.cpp:89
const char * GetModule(void) const
SDiagMessage::TUID TUID
Definition: ncbidiag.hpp:1973
bool m_CanDeleteHandler
Can handler be deleted?
Definition: ncbidiag.hpp:2998
const CNcbiDiag & SetModule(const char *module) const
Set module name.
Definition: ncbidiag.cpp:7867
size_t GetDroppedRequestsCount(void) const
Definition: ncbidiag.hpp:2842
unique_ptr< CRequestRateControl > m_ErrLogRC
Definition: ncbidiag.hpp:2388
SDiagMessageData * m_Data
Definition: ncbidiag.hpp:1750
virtual CNcbiOstream * GetStream(void)
Definition: ncbidiag.hpp:2589
bool IgnoreDiagDieLevel(bool ignore)
Ignore the die level settings.
Definition: ncbidiag.cpp:6276
@ eDPF_UID
Definition: ncbidiag.hpp:710
@ eDPF_SerialNo_Thread
Definition: ncbidiag.hpp:707
@ eDPF_TID
Thread ID.
Definition: ncbidiag.hpp:703
@ eDPF_AtomicWrite
This flag is deprecated and ignored - all log writes are atomic.
Definition: ncbidiag.hpp:761
@ eDPF_ErrCodeUseSeverity
Use severity from error code (default)
Definition: ncbidiag.hpp:701
@ eDPF_Location
Include class and function if any.
Definition: ncbidiag.hpp:702
@ eDPF_PID
Definition: ncbidiag.hpp:705
@ eDPF_Iteration
Definition: ncbidiag.hpp:709
@ eDPF_OmitSeparator
No '—' separator before message.
Definition: ncbidiag.hpp:752
@ eDPF_MergeLines
Escape EOLs.
Definition: ncbidiag.hpp:749
@ eDPF_ErrCodeMsgInFront
Put ErrCode text in front of the message.
Definition: ncbidiag.hpp:748
@ eDPF_ErrCodeExplanation
Error explanation (default)
Definition: ncbidiag.hpp:700
@ eDPF_IsNote
Print "Note[X]" severity name.
Definition: ncbidiag.hpp:755
@ eDPF_DateTime
Include date and time.
Definition: ncbidiag.hpp:698
@ eDPF_ErrorID
Error code and subcode (default)
Definition: ncbidiag.hpp:696
@ eDPF_RequestId
Definition: ncbidiag.hpp:708
@ eDPF_Log
Print the posted message only; without severity, location, prefix, etc.
Definition: ncbidiag.hpp:745
@ eDPF_Severity
Severity (default)
Definition: ncbidiag.hpp:695
@ eDPF_OmitInfoSev
No sev. indication if eDiag_Info.
Definition: ncbidiag.hpp:751
@ eDPF_Default
Use global default flags (merge with).
Definition: ncbidiag.hpp:769
@ eDPF_ErrSubCode
Definition: ncbidiag.hpp:713
@ eDPF_IsConsole
Send the message to 'console' regardless of it's severity.
Definition: ncbidiag.hpp:765
@ eDPF_Line
Source line.
Definition: ncbidiag.hpp:693
@ eDPF_PreMergeLines
Obsolete. Use eDPF_MergeLines.
Definition: ncbidiag.hpp:750
@ eDPF_IsMessage
Definition: ncbidiag.hpp:756
@ eDPF_Trace
Default flags to use when tracing.
Definition: ncbidiag.hpp:720
@ eDPF_File
File name (not full path)
Definition: ncbidiag.hpp:691
@ eDPF_UseExactUserFlags
Use flags provided by user as-is, do not allow CNcbiDiag to replace "important" flags by the globally...
Definition: ncbidiag.hpp:780
@ eDPF_ImportantFlagsMask
Important bits which should be taken from the globally set flags even if a user attempts to override ...
Definition: ncbidiag.hpp:774
@ eDPF_ErrCodeMessage
Error code message (default)
Definition: ncbidiag.hpp:699
@ eDPF_ErrCode
Definition: ncbidiag.hpp:712
@ eDPF_Exception
Default flags to use for exception formatting.
Definition: ncbidiag.hpp:742
@ eDPF_LongFilename
Full file path.
Definition: ncbidiag.hpp:692
@ eDPF_AppLog
Post message to application log.
Definition: ncbidiag.hpp:754
@ eDPF_SerialNo
Definition: ncbidiag.hpp:706
@ eDPF_Prefix
Prefix (default)
Definition: ncbidiag.hpp:694
@ eDPF_All
All flags (except for the "unusual" ones!)
Definition: ncbidiag.hpp:716
@ eDiagSC_Enable
Enable change severity level.
Definition: ncbidiag.hpp:667
@ eDiagSC_Disable
Disable change severity level.
Definition: ncbidiag.hpp:666
@ eDiagSC_Unknown
Status of changing severity is unknown (first call)
Definition: ncbidiag.hpp:665
@ eDCM_Discard
Discard the collected messages without flushing.
Definition: ncbidiag.hpp:1803
@ eDCM_Init
Start collecting messages (with limit), do nothing if already initialized.
Definition: ncbidiag.hpp:1797
@ eDCM_NoChange
Continue collecting messages if already started.
Definition: ncbidiag.hpp:1801
@ eDCM_InitNoLimit
Start collecting messages without limit (must stop collecting later using eDCM_Flush or eDCM_Discard)...
Definition: ncbidiag.hpp:1799
@ eDCM_Flush
Flush the collected messages and stop collecting.
Definition: ncbidiag.hpp:1802
@ eDS_Default
Try standard log file (app.name + ".log") in /log/, use stderr on failure.
Definition: ncbidiag.hpp:1788
@ eDS_ToMemory
Keep in a temp.memory buffer, see FlushMessages()
Definition: ncbidiag.hpp:1783
@ eDS_User
Leave as was previously set (or not set) by user.
Definition: ncbidiag.hpp:1785
@ eDS_Disable
Don't write it anywhere.
Definition: ncbidiag.hpp:1784
@ eDS_AppSpecific
Call the application's SetupDiag_AppSpecific()
Definition: ncbidiag.hpp:1786
@ eDS_ToStdlog
Try standard log file (app.name + ".log") in /log/ and current directory, use stderr if both fail.
Definition: ncbidiag.hpp:1781
@ eDS_ToStdout
To standard output stream.
Definition: ncbidiag.hpp:1779
@ eDS_ToStderr
To standard error stream.
Definition: ncbidiag.hpp:1780
@ eDS_ToSyslog
To system log daemon.
Definition: ncbidiag.hpp:1790
@ ePostNumber_NoIncrement
Get post number without incrementing it.
Definition: ncbidiag.hpp:1810
@ ePostNumber_Increment
Increment and return the new post number.
Definition: ncbidiag.hpp:1811
@ eEvent_RequestStop
Finish processing request.
Definition: ncbidiag.hpp:1643
@ eEvent_RequestStart
Start processing request.
Definition: ncbidiag.hpp:1642
@ eEvent_Start
Application start.
Definition: ncbidiag.hpp:1639
@ eEvent_Extra
Other application events.
Definition: ncbidiag.hpp:1641
@ eEvent_Stop
Application exit.
Definition: ncbidiag.hpp:1640
@ eDT_Enable
Enable messages of severity "eDiag_Trace".
Definition: ncbidiag.hpp:1548
@ eDT_Disable
Ignore messages of severity "eDiag_Trace".
Definition: ncbidiag.hpp:1547
@ eDT_Default
Restores the default tracing context.
Definition: ncbidiag.hpp:1546
@ ePrint
Print all collected messages as is.
Definition: ncbidiag.hpp:1302
@ eDiscard
Discard collected messages, default.
Definition: ncbidiag.hpp:1303
@ eLogRate_Err
Error log.
Definition: ncbidiag.hpp:2276
@ eLogRate_App
Application log.
Definition: ncbidiag.hpp:2275
@ eDisable_All
Disable all applog events (default).
Definition: ncbidiag.hpp:2307
@ eDiagFile_Trace
Trace log file.
Definition: ncbidiag.hpp:2448
@ eDiagFile_Perf
Perf log file.
Definition: ncbidiag.hpp:2449
@ eDiagFile_Err
Error log file.
Definition: ncbidiag.hpp:2446
@ eDiagFile_All
All log files.
Definition: ncbidiag.hpp:2450
@ eDiagFile_Log
Access log file.
Definition: ncbidiag.hpp:2447
@ eDiagAppState_RequestEnd
RE.
Definition: ncbidiag.hpp:794
@ eDiagAppState_AppEnd
AE.
Definition: ncbidiag.hpp:791
@ eDiagAppState_AppBegin
AB.
Definition: ncbidiag.hpp:789
@ eDiagAppState_AppRun
A.
Definition: ncbidiag.hpp:790
@ eDiagAppState_RequestBegin
RB.
Definition: ncbidiag.hpp:792
@ eDiagAppState_NotSet
Reserved value, never used in messages.
Definition: ncbidiag.hpp:788
@ eDiagAppState_Request
R.
Definition: ncbidiag.hpp:793
@ eDiag_Trace
Trace message.
Definition: ncbidiag.hpp:655
@ eDiag_Info
Informational message.
Definition: ncbidiag.hpp:649
@ eDiag_Error
Error message.
Definition: ncbidiag.hpp:651
@ eDiag_Warning
Warning message.
Definition: ncbidiag.hpp:650
@ eDiag_Fatal
Fatal error – guarantees exit(or abort)
Definition: ncbidiag.hpp:653
@ eDiagSevMin
Verbosity level for min. severity.
Definition: ncbidiag.hpp:658
@ eDiag_Critical
Critical error message.
Definition: ncbidiag.hpp:652
@ eDiagSevMax
Verbosity level for max. severity.
Definition: ncbidiag.hpp:659
@ eProp_Default
Auto-mode for known properties, local for others.
Definition: ncbidiag.hpp:2013
@ eProp_Global
The property is global for the application.
Definition: ncbidiag.hpp:2014
@ eDiagFilter_All
for all non-FATAL
Definition: ncbidiag.hpp:2541
@ eDiagFilter_Post
for all non-TRACE, non-FATAL
Definition: ncbidiag.hpp:2540
@ eDiagFilter_Trace
for TRACEs only
Definition: ncbidiag.hpp:2539
void Read(CObjectIStream &in, TObjectPtr object, const CTypeRef &type)
Definition: serial.cpp:60
void Write(CObjectOStream &out, TConstObjectPtr object, const CTypeRef &type)
Definition: serial.cpp:55
#define NCBI_DEPRECATED
int64_t Int8
8-byte (64-bit) signed integer
Definition: ncbitype.h:104
uint64_t Uint8
8-byte (64-bit) unsigned integer
Definition: ncbitype.h:105
#define END_NCBI_SCOPE
End previously defined NCBI scope.
Definition: ncbistl.hpp:104
#define BEGIN_NCBI_SCOPE
Define ncbi namespace.
Definition: ncbistl.hpp:101
IO_PREFIX::ostream CNcbiOstream
Portable alias for ostream.
Definition: ncbistre.hpp:149
IO_PREFIX::istream CNcbiIstream
Portable alias for istream.
Definition: ncbistre.hpp:146
IO_PREFIX::ios CNcbiIos
Portable alias for ios.
Definition: ncbistre.hpp:140
#define NCBI_XNCBI_EXPORT
Definition: ncbi_export.h:1299
FILE * file
char * buf
int len
static MDB_envinfo info
Definition: mdb_load.c:37
Uint4 GetHost(TEndpointKey key)
mdb_mode_t mode
Definition: lmdb++.h:62
const GenericPointer< typename T::ValueType > T2 value
Definition: pointer.h:1227
const CharType(& source)[N]
Definition: pointer.h:1149
static void s_EscapeNewlines(const void *src_buf, size_t src_size, size_t *src_read, void *dst_buf, size_t dst_size, size_t *dst_written)
Escape newlines in the string.
Definition: ncbi_c_log.c:1214
EIPRangeType t
Definition: ncbi_localip.c:102
CDiagContext_Extra g_PostPerf(int status, double timespan, SDiagMessage::TExtraArgs &args)
Definition: ncbidiag.cpp:8461
std::istream & in(std::istream &in_, double &x_)
@ fNone
static SLJIT_INLINE sljit_ins msg(sljit_gpr r, sljit_s32 d, sljit_gpr x, sljit_gpr b)
SDiagErrCodeDescription –.
Definition: ncbidiag.hpp:3012
SDiagMessage –.
Definition: ncbidiag.hpp:1597
Template structure used to point out wrong error subcode in ERR_POST_X, STD_CATCH_X and alike macros.
Definition: ncbidiag.hpp:401
Template structure used to point out incorrect usage of NCBI_DEFINE_ERR_SUBCODE_X macro i....
Definition: ncbidiag.hpp:418
Definition: inftrees.h:24
Definition: type.c:6
else result
Definition: token2.c:20
static wxAcceleratorEntry entries[3]
Modified on Sun Nov 08 14:01:12 2026 by modify_doxy.py rev. 717554