56 #include <unordered_set>
59 #if defined(NCBI_OS_UNIX)
61 # include <sys/utsname.h>
64 #if defined(NCBI_OS_MSWIN)
66 #elif defined (NCBI_OS_DARWIN)
67 # include <crt_externs.h>
68 # define environ (*_NSGetEnviron())
70 extern char** environ;
74 #define NCBI_USE_ERRCODE_X Corelib_Diag
95 bool diag_unlocked = s_DiagMutex.TryLock();
101 "Cannot switch diagnostic to RW-lock - mutex is locked.");
103 s_DiagMutex.Unlock();
110 if (!diag_unlocked) {
113 "Cannot switch diagnostic to mutex - RW-lock is locked.");
147 s_DiagPostMutex.Lock();
161 s_DiagPostMutex.Unlock();
164 s_DiagMutex.Unlock();
235 #if defined(NCBI_POSIX_THREADS) && defined(HAVE_PTHREAD_ATFORK)
240 static void s_NcbiDiagPreFork(
void)
244 static void s_NcbiDiagPostFork(
void)
246 s_DiagMutex.Unlock();
259 DIAG_OLD_POST_FORMAT);
266 DIAG_AUTOWRITE_CONTEXT);
272 DIAG_PRINT_SYSTEM_TID);
280 DIAG_ASSERT_ON_ABORT);
285 DIAG_LOG_SIZE_LIMIT);
291 DIAG_MAX_LINE_LENGTH);
326 lim.
Set(NStr::StringToNumeric<CLogRateLimit::TValue>(s));
346 DIAG_APPLOG_RATE_PERIOD);
358 DIAG_ERRLOG_RATE_PERIOD);
370 DIAG_TRACELOG_RATE_PERIOD);
421 DIAG_LOG_ENVIRONMENT);
434 DIAG_DISABLE_APPLOG_MESSAGES);
534 x_Init(print_severity, collect_severity, action);
551 psev = CDiagBuffer::sm_PostSeverity;
555 ? psev : print_severity;
557 ? csev : collect_severity;
615 str_rev_str(
const char* begin_str,
const char* end_str,
const char* str_search)
617 if (begin_str ==
NULL)
621 if (str_search ==
NULL)
624 const char* search_char = str_search + strlen(str_search);
625 const char* cur_char = end_str;
631 }
while(*cur_char != *search_char && cur_char != begin_str);
632 if (*cur_char != *search_char)
635 while (search_char != str_search);
657 const char* curr_funct,
662 m_CurrFunctName(curr_funct),
680 const string& curr_funct,
681 const string& module)
700 const char* cur_extension = strrchr(
m_File,
'.');
701 if (cur_extension ==
NULL)
704 if (*(cur_extension + 1) !=
'\0') {
710 return strcmp(cur_extension,
"cpp") == 0 ||
711 strcmp(cur_extension,
"C") == 0 ||
712 strcmp(cur_extension,
"c") == 0 ||
713 strcmp(cur_extension,
"cxx") == 0;
771 if (*(stop - 1) != rsep)
return stop;
773 const char* pos = stop - 2;
774 for (; pos > start; pos--) {
778 else if (*pos == lsep) {
779 if (--balance == 0)
break;
782 return (pos <= start) ?
NULL : pos;
812 const char* start_str =
NULL;
815 const char* start_str_tmp =
817 bool has_class = start_str_tmp !=
NULL;
818 if (start_str_tmp !=
NULL) {
819 start_str = start_str_tmp + 2;
822 if (start_str_tmp !=
NULL) {
823 start_str = start_str_tmp + 1;
827 const char* cur_funct_name =
829 while (cur_funct_name && *cur_funct_name &&
830 (*cur_funct_name ==
'*' || *cur_funct_name ==
'&')) {
833 size_t cur_funct_name_len = end_str - cur_funct_name;
840 const char* cur_class_name =
842 while (cur_class_name && *cur_class_name &&
843 (*cur_class_name ==
'*' || *cur_class_name ==
'&')) {
846 size_t cur_class_name_len = end_str - cur_class_name;
860 #if defined(NCBI_POSIX_THREADS) && defined(HAVE_PTHREAD_ATFORK)
861 pthread_atfork(s_NcbiDiagPreFork,
906 #define USE_TLS_DATA_CACHE
907 #ifdef USE_TLS_DATA_CACHE
919 : m_DiagBuffer(new CDiagBuffer),
921 m_ThreadPostNumber(0),
922 m_DiagCollectionSize(0)
932 #ifdef USE_TLS_DATA_CACHE
971 #ifdef USE_TLS_DATA_CACHE
982 switch (thread_data_state) {
991 cerr <<
"FATAL ERROR: inappropriate recursion initializing NCBI"
992 " diagnostic framework." << endl;
1001 cerr <<
"FATAL ERROR: NCBI diagnostic framework no longer"
1002 " initialized." << endl;
1027 #ifdef USE_TLS_DATA_CACHE
1068 "Using the same CRequestContext in multiple threads is unsafe!"
1096 TCollectGuards::iterator itg = find(
1103 unique_ptr<CDiagLock> lock;
1109 if (itc->m_ThrPost >= start
1111 itc->m_Severity = cap;
1122 if (lock.get() ==
nullptr) {
1138 if (itc->m_Severity ==
eDiag_Trace && !allow_trace) {
1141 if (itc->m_Severity < post_sev) {
1147 if (discarded > 0) {
1149 " messages due to collection limit. Set "
1150 "DIAG_COLLECT_LIMIT to increase the limit.");
1213 "NS",
"PB",
"P",
"PE",
"RB",
"R",
"RE"
1303 m_AppNameSet(
false),
1304 m_LoggedHitId(
false),
1306 m_ExitCodeSet(
false),
1312 GetLogRate_Limit(eLogRate_App),
1313 CTimeSpan((long)GetLogRate_Period(eLogRate_App)),
1318 GetLogRate_Limit(eLogRate_Err),
1319 CTimeSpan((long)GetLogRate_Period(eLogRate_Err)),
1324 GetLogRate_Limit(eLogRate_Trace),
1325 CTimeSpan((long)GetLogRate_Period(eLogRate_Trace)),
1329 m_AppLogSuspended(
false),
1330 m_ErrLogSuspended(
false),
1331 m_TraceLogSuspended(
false)
1479 bool approved =
true;
1548 Print(
"action",
"fork").
1549 Print(
"parent_guid",
ctx.GetStringUID(old_uid)).
1618 return (TUID(base) << 48) |
1619 ((TUID(pid) & 0xFFFF) << 32) |
1620 ((TUID(
t) & 0xFFFFFFF) << 4) |
1627 const string& host =
GetHost();
1628 for (
auto c : host) {
1641 #if defined(NCBI_OS_UNIX)
1644 if (uname(&
buf) >= 0) {
1645 const char* s =
buf.nodename;
1679 int hi =
int((uid >> 32) & 0xFFFFFFFF);
1680 int lo =
int(uid & 0xFFFFFFFF);
1681 snprintf(
buf, buflen,
"%08X%08X", hi, lo);
1709 uid &= ~((
TUID)0xFFFFFFF << 4);
1711 return uid | ((
TUID(
t) & 0xFFFFFFF) << 4);
1732 if ( !is_default ) {
1736 rid = ((
Uint8)0xFFFFFF) << 16;
1739 Uint8 lo = tid | rid | us;
1743 snprintf(
buf, 33,
"%08X%08X%08X%08X", b3, b2, b1, b0);
1769 if ( !
m_Host->IsEmpty() ) {
1770 return m_Host->GetOriginalString();
1778 if (ncbi_host && *ncbi_host) {
1780 return m_Host->GetOriginalString();
1783 #if defined(NCBI_OS_UNIX)
1787 if (uname(&
buf) >= 0) {
1789 return m_Host->GetOriginalString();
1794 #if defined(NCBI_OS_MSWIN)
1797 if ( compname && *compname ) {
1799 return m_Host->GetOriginalString();
1805 if ( servaddr && *servaddr ) {
1808 return m_Host->GetOriginalString();
1814 if ( !
m_Host->IsEmpty() ) {
1815 return m_Host->GetEncodedString();
1822 return m_Host->GetEncodedString();
1828 return m_Host->GetOriginalString();
1834 return m_Host->GetEncodedString();
1888 ERR_POST(
"Application name cannot be changed.");
1895 ERR_POST(
"Illegal characters in application name: '" << app_name <<
1896 "', using URL-encode.");
1932 const string&
value,
1979 if ( !
value.empty() ) {
2090 gprop->first +
"=" + gprop->second);
2102 static const char* kCloudIdFile =
"/etc/ncbi/cloudid";
2103 CFile cloudid(kCloudIdFile);
2104 if ( cloudid.
Exists() ) {
2107 while (!
in.eof() &&
in.good()) {
2110 size_t sep = s.find(
'\t');
2111 if (sep ==
NPOS)
continue;
2113 string value = s.substr(sep + 1);
2123 for (
char **
env = environ; *
env; ++
env) {
2132 f.LogFields(env_map);
2149 ctx.x_LogHitID(
true);
2169 : m_EventType(event_type),
2171 m_Counter(new
int(1)),
2176 m_AllowBadNames(
false)
2186 m_Counter(new
int(1)),
2188 m_PerfStatus(status),
2189 m_PerfTime(timespan),
2191 m_AllowBadNames(
false)
2193 if (args.empty())
return;
2203 m_Typed(args.m_Typed),
2204 m_PerfStatus(args.m_PerfStatus),
2205 m_PerfTime(args.m_PerfTime),
2206 m_Flushed(args.m_Flushed),
2207 m_AllowBadNames(args.m_AllowBadNames)
2228 if ( !role.empty() ) {
2229 Print(
"ncbi_role", role);
2231 if ( !loc.empty() ) {
2232 Print(
"ncbi_location", loc);
2252 Print(
"ncbi_app_package_version", pkv);
2256 initializer_list<SBuildInfo::EExtra> bi_num = {
2265 if (!
value.empty()) {
2271 #if defined(NCBI_TEAMCITY_PROJECT_NAME)
2274 #if defined(NCBI_TEAMCITY_BUILDCONF_NAME)
2277 #if defined(NCBI_TEAMCITY_BUILD_NUMBER)
2280 #if defined(NCBI_TEAMCITY_BUILD_ID)
2305 initializer_list<SBuildInfo::EExtra> bi_num =
2311 if (!
value.empty()) {
2317 #if defined(NCBI_PRODUCTION_VER)
2318 Print(
"ncbi_app_prod_version", NStr::NumericToString<Uint8>(NCBI_PRODUCTION_VER));
2319 #elif defined(NCBI_DEVELOPMENT_VER)
2322 #if defined(NCBI_SC_VERSION)
2323 Print(
"ncbi_app_sc_version", NStr::NumericToString<Uint8>(NCBI_SC_VERSION));
2325 #if defined(NCBI_SUBVERSION_REVISION)
2356 bool app_state_updated =
false;
2361 app_state_updated =
true;
2368 app_state_updated =
true;
2397 if ( app_state_updated ) {
2421 if (
this != &args) {
2449 "Attempt to set request start/stop arguments after flushing");
2483 "exec_time_msec_bit",
2495 "geo_latitude_hundredths",
2496 "geo_longitude_hundredths",
2497 "session_pageviews",
2502 "time_to_last_ping",
2509 "self_url_file_ext",
2510 "self_url_top_level_dir",
2511 "self_url_directory",
2523 "has_duplicate_nexus",
2524 "has_duplicate_phid",
2528 "has_multiple_phid",
2535 "multiple_session_hit",
2536 "multiple_session_ip",
2537 "ncbi_phid_first_render",
2538 "phid_from_other_request",
2539 "phid_stack_ambiguous_relationship",
2540 "phid_stack_has_fake_child",
2541 "phid_stack_has_fake_parent",
2542 "phid_stack_missing_child",
2543 "phid_stack_missing_parent",
2544 "phid_stack_multivalued",
2546 "session_bot_by_ip",
2547 "session_bot_by_rate",
2548 "session_bot_by_user_agent",
2553 "browser_major_version",
2562 "applog_db_size_hit_fraction",
2563 "applog_db_machine",
2566 "applog_db_date_tag",
2567 "applog_db_date_range",
2569 "applog_db_create_time",
2570 "applog_db_modify_time",
2573 "applog_db_agent_host",
2574 "applog_db_agent_pid",
2575 "applog_db_agent_tid",
2576 "applog_db_volume_served_time",
2577 "phid_stack_missing_parent",
2578 "phid_stack_missing_child",
2579 "phid_stack_has_fake_child",
2580 "phid_stack_has_fake_parent",
2581 "phid_stack_ambiguous_relationship",
2582 "phid_stack_multivalued",
2583 "ncbi_phid_first_render",
2584 "multiple_session_hit",
2587 "has_duplicate_nexus",
2589 "has_multiple_phid",
2591 "session_bot_by_rate",
2592 "session_bot_by_user_agent",
2594 "session_bot_by_ip",
2596 "multiple_session_ip",
2609 for (
int i = 0;
i < sz; ++
i) {
2638 if (kw.find(name) == kw.end()) {
2639 m_Args->rbegin()->first.assign(name);
2642 string renamed =
"auto_renamed_applog_keyword__" + name;
2643 m_Args->rbegin()->first.assign(renamed);
2645 <<
"' is a reserved NCBI AppLog keyword, so it has been renamed to "
2682 #if !NCBI_INT8_IS_LONG
2693 #elif SIZEOF_LONG_LONG
2765 bool app_state_updated =
false;
2769 app_state_updated =
true;
2772 if ( app_state_updated ) {
2781 bool app_state_updated =
false;
2784 app_state_updated =
true;
2787 if ( app_state_updated ) {
2863 NCBI_LOG_SESSION_ID);
2883 if ( sid.empty() ) {
2928 NCBI_LOG_CLIENT_IP);
3013 if ( !phid.empty() ) {
3014 const char* c_env_job_id = getenv(
"JOB_ID");
3015 string env_job_id = c_env_job_id ?
string(c_env_job_id):
"";
3016 const char* c_env_task_id = getenv(
"SGE_TASK_ID");
3017 string env_task_id = c_env_task_id ?
string(c_env_task_id) :
"";
3018 if (env_task_id.find_first_not_of(
"0123456789") !=
NPOS) {
3023 if (!env_job_id.empty() && !env_task_id.empty()) {
3030 string jid =
".000" + env_job_id;
3031 string tid =
".00" + env_task_id;
3032 size_t jid_pos = phid.find(jid);
3033 if (jid_pos ==
NPOS) {
3039 if (phid.find(tid, jid_pos + jid.size()) ==
NPOS) {
3096 unique_ptr<string> role(
new string);
3098 if (env_role && *env_role) {
3116 unique_ptr<string> loc(
new string);
3118 if (env_loc && *env_loc) {
3168 const string& host = msg.
GetHost();
3179 << setfill(
' ') << setw(
kDiagW_AppState) << setiosflags(IOS_BASE::left)
3180 << app_state << resetiosflags(IOS_BASE::left)
3181 <<
' ' << setw(0) << setfill(
' ') << uid <<
' '
3185 << setfill(
' ') << setiosflags(IOS_BASE::left)
3192 << resetiosflags(IOS_BASE::left) << setw(0)
3201 if (
ctx.IsRunning() ) {
3205 "Duplicate request-start or missing request-stop");
3209 if ( !
ctx.IsSetExplicitClientIP() ) {
3211 if ( !
ip.empty() ) {
3212 ctx.SetClientIP(
ip);
3225 string log_args = s_LogEnvironment->
Get();
3226 if ( !log_args.empty() ) {
3227 list<string> log_args_list;
3231 extra.
Print(
"LogEnvironment",
"true");
3239 ITERATE(list<string>, it, log_args_list) {
3240 const string&
val =
env.Get(*it);
3248 log_args = s_LogRegistry->
Get();
3249 if ( !log_args.empty() ) {
3250 list<string> log_args_list;
3254 extra.
Print(
"LogRegistry",
"true");
3261 ITERATE(list<string>, it, log_args_list) {
3262 string section, name;
3264 const string&
val = reg.
Get(section, name);
3275 const string& message)
3282 bool need_space =
false;
3303 if ( !
ctx.IsRunning() ) {
3307 "Duplicate request-stop or missing request-start");
3309 str.append(to_string(
ctx.GetRequestStatus())).append(1,
' ')
3310 .append(
ctx.GetRequestTimer().AsString()).append(1,
' ')
3311 .append(to_string(
ctx.GetBytesRd())).append(1,
' ')
3312 .append(to_string(
ctx.GetBytesWr()));
3319 if ( !message.empty() ) {
3323 str.append(message);
3336 CDiagBuffer::DiagHandler(mess);
3433 size_t min_pos = exe_path.length();
3437 if (!it->empty() && (*it)[0] !=
'/') {
3439 string mask =
"/" + *it;
3440 if (
mask[
mask.length() - 1] !=
'/') {
3443 size_t pos = exe_path.find(
mask);
3444 if (pos < min_pos) {
3451 if (exe_path.substr(0, it->length()) == *it) {
3457 if ( !web_dir.empty() ) {
3471 return TLogTruncateParam::GetDefault();
3477 TLogTruncateParam::SetDefault(
value);
3483 if ( !logname.empty() ) {
3514 return config->GetString(
"LOG", name, defval);
3516 string envname =
"NCBI_CONFIG__LOG__";
3529 return config->GetBool(
"LOG", name, defval);
3531 string envname =
"NCBI_CONFIG__LOG__";
3548 const char* cmd_logfile)
3560 CDiagBuffer::GetSeverityChangeEnabledFirstTime();
3569 ctx.InitMessages(
size_t(-1));
3594 bool log_set =
false;
3595 bool to_applog =
false;
3596 string old_log_name;
3597 string new_log_name;
3600 if ( old_handler ) {
3605 if ( config_logfile.empty() ) {
3615 if (cmdline_first && cmd_logfile) {
3618 new_log_name = cmd_logfile;
3623 if (!log_set && !applog_first && !config_logfile.empty()) {
3626 new_log_name = config_logfile;
3630 if (!log_set && !cmdline_first && cmd_logfile &&
3634 new_log_name = cmd_logfile;
3659 ctx.InitMessages(
size_t(-1));
3699 #if defined(NCBI_OS_UNIX)
3711 if ( !log_base.empty() ) {
3715 if ( !def_log_dir.empty() ) {
3719 new_log_name = log_name;
3728 new_log_name = log_name;
3736 new_log_name = config_logfile;
3743 new_log_name = log_name;
3753 new_log_name = log_name;
3757 _TRACE_X(3,
"Failed to set log file to " +
3761 if (!log_set && !cmdline_first && cmd_logfile) {
3764 new_log_name = cmd_logfile;
3770 if (!log_set && log_base.empty()) {
3774 new_log_name = default_fallback;
3778 _TRACE_X(4,
"Failed to set log file to " <<
3781 const char* log_name = TTeeToStderr::GetDefault() ?
3783 if (!log_set && old_log_name != log_name) {
3788 new_log_name = log_name;
3802 ctx.SetOldPostFormat(
false);
3818 if (log_set && new_handler && new_handler->
GetLogName() == old_log_name) {
3826 if ( log_set && new_handler ) {
3827 ctx.FlushMessages(*new_handler);
3833 if ( log_set && new_handler ) {
3834 ctx.FlushMessages(*new_handler);
3838 ctx.DiscardMessages();
3842 ctx.ResetLogRates();
3852 s_ProcessPostCount.
Add(1) : s_ProcessPostCount.
Get());
3882 return s_DiagContext.
Get();
3889 #ifdef NCBI_LOG_FIELDS_CUSTOM
3893 typedef NCBI_PARAM_TYPE(Log, Ncbi_Log_Fields_Custom) TCustomLogFields;
3907 #ifdef NCBI_LOG_FIELDS_CUSTOM
3908 string custom_fields = TCustomLogFields::GetDefault();
3924 if ( it->empty() )
continue;
3965 return sx_GetPostFlags();
3971 bool CDiagBuffer::sm_IgnoreToDie =
false;
3975 bool CDiagBuffer::sm_TraceEnabled;
3978 const char* CDiagBuffer::sm_SeverityName[
eDiag_Trace+1] = {
3979 "Info",
"Warning",
"Error",
"Critical",
"Fatal",
"Trace" };
3997 DEBUG_STACK_TRACE_LEVEL);
4004 static bool s_DiagInitialized =
false;
4005 if (!s_DiagInitialized) {
4007 #ifdef NCBI_OS_MSWIN
4015 s_DiagInitialized =
true;
4036 bool CDiagBuffer::sm_CanDeleteHandler =
true;
4038 bool CDiagBuffer::sm_CanDeleteErrCodeInfo =
false;
4044 static bool s_DefaultDiagHandlerInitialized =
false;
4045 if ( !s_DefaultDiagHandlerInitialized ) {
4046 s_DefaultDiagHandlerInitialized =
true;
4048 if ( TTeeToStderr::GetDefault() ) {
4072 CDiagBuffer::CDiagBuffer(
void)
4074 m_InitialStreamFlags(m_Stream->
flags()),
4080 CDiagBuffer::~CDiagBuffer(
void)
4083 if (m_Diag || m_Stream->pcount())
4098 if ( CDiagBuffer::sm_Handler ) {
4100 if ( CDiagBuffer::sm_Handler ) {
4103 bool show_warning =
false;
4106 mess.
m_Prefix = diag_buf.m_PostPrefix.empty() ?
4107 0 : diag_buf.m_PostPrefix.c_str();
4115 if (
ctx.ApproveMessage(mess, &show_warning) ) {
4137 CDiagBuffer::sm_Handler->
Post(phid_msg);
4139 CDiagBuffer::sm_Handler->
Post(mess);
4141 else if ( show_warning ) {
4145 string limit_name =
"error";
4149 limit_name =
"applog";
4154 limit_name =
"trace";
4157 string txt =
"Maximum logging rate for " + limit_name +
" ("
4161 +
" sec) exceeded, suspending the output.";
4164 txt.c_str(), txt.length(),
4169 err_code_x::eErrCodeX_Corelib_Diag,
4175 CDiagBuffer::sm_Handler->
Post(err_msg);
4185 bool CDiagBuffer::SeverityDisabled(
EDiagSev sev)
4191 bool allow_trace = GetTraceEnabled();
4202 return (sev < post_sev) && (sev < sm_DieSeverity || sm_IgnoreToDie);
4207 bool CDiagBuffer::SeverityPrintable(
EDiagSev sev)
4213 bool allow_trace = GetTraceEnabled();
4224 return !((sev < post_sev) && (sev < sm_DieSeverity || sm_IgnoreToDie));
4228 bool CDiagBuffer::SetDiag(
const CNcbiDiag& diag)
4230 if ( m_InUse || !m_Stream ) {
4236 if (!is_console && SeverityDisabled(sev)) {
4240 if (m_Diag != &diag) {
4263 static bool Check();
4278 #ifndef NCBI_THREADS
4279 thread::id stored_thread_id;
4280 thread::id this_thread_id = this_thread::get_id();
4283 if (
sm_ThreadID.compare_exchange_strong(stored_thread_id, this_thread_id))
return false;
4286 if (stored_thread_id == this_thread_id)
return false;
4288 bool reported =
false;
4291 if (
sm_Reported.compare_exchange_strong(reported,
true))
return true;
4306 const auto msg =
"Detected different threads using C++ Toolkit built in single thread mode."sv;
4325 void CDiagBuffer::Flush(
void)
4327 if ( m_InUse || !m_Diag ) {
4328 if ( !m_InUse && m_Stream && !
IsOssEmpty(*m_Stream) ) {
4331 m_Stream->rdbuf()->PUBSEEKOFF(0, IOS_BASE::beg,
IOS_BASE::out);
4338 EDiagSev sev = m_Diag->GetSeverity();
4339 bool is_console = (m_Diag->GetPostFlags() &
eDPF_IsConsole) != 0;
4340 bool is_disabled = SeverityDisabled(sev);
4343 if (!is_console && is_disabled) {
4351 flags |= sm_TraceFlags;
4358 if ( m_Diag->CheckFilters() ) {
4364 m_Diag->GetErrorCode(),
4365 m_Diag->GetErrorSubCode(),
4367 m_Diag->GetModule(),
4369 m_Diag->GetFunction());
4370 PrintMessage(mess, *m_Diag);
4376 PrintMessage(mess, *m_Diag);
4379 #if defined(NCBI_COMPILER_KCC)
4386 m_Stream->flags(m_InitialStreamFlags);
4387 # ifdef NCBI_SHUN_OSTRSTREAM
4395 if (sev >= sm_DieSeverity && sev !=
eDiag_Trace && !sm_IgnoreToDie) {
4398 #ifdef NCBI_COMPILER_MSVC
4400 int old_mode = _set_error_mode(_OUT_TO_MSGBOX);
4402 _set_error_mode(old_mode);
4417 if (!SeverityPrintable(sev)) {
4422 bool is_disabled = SeverityDisabled(sev);
4423 if (!is_disabled || (is_console && can_collect)) {
4440 bool CDiagBuffer::GetTraceEnabledFirstTime(
void)
4449 sm_TraceEnabled = (sm_TraceDefault ==
eDT_Enable);
4450 return sm_TraceEnabled;
4454 bool CDiagBuffer::GetSeverityChangeEnabledFirstTime(
void)
4470 void CDiagBuffer::UpdatePrefix(
void)
4472 m_PostPrefix.erase();
4474 if (
prefix != m_PrefixList.begin()) {
4475 m_PostPrefix +=
"::";
4487 const char*
buf,
size_t len,
4488 const char*
file,
size_t line,
4490 int err_code,
int err_subcode,
4491 const char* err_text,
4494 const char*
function)
4495 : m_Event(eEvent_Start),
4496 m_TypedExtra(
false),
4498 m_PrintStackTrace(
false),
4500 m_Format(eFormat_Auto),
4501 m_AllowBadExtraNames(
false)
4523 switch (app_state) {
4559 m_Event(eEvent_Start),
4560 m_TypedExtra(
false),
4562 m_PrintStackTrace(
false),
4564 m_Format(eFormat_Auto),
4565 m_AllowBadExtraNames(
false)
4601 m_Event(eEvent_Start),
4602 m_TypedExtra(
false),
4604 m_PrintStackTrace(
false),
4606 m_Format(eFormat_Auto),
4607 m_AllowBadExtraNames(
false)
4615 if (&message !=
this) {
4685 if (pos >= message.length()) {
4687 "Failed to parse diagnostic message");
4691 if (message[pos + width] != sep) {
4693 "Missing separator after integer");
4697 width = message.find(sep, pos);
4698 if (width ==
NPOS) {
4700 "Missing separator after integer");
4714 bool optional =
false)
4716 if (pos >= message.length()) {
4718 "Failed to parse diagnostic message");
4721 pos = message.find(sep, pos1);
4725 "Failed to parse diagnostic message");
4730 if ( pos == pos1 + 1 && !optional ) {
4733 "Failed to parse diagnostic message");
4737 pos = message.find_first_not_of(sep, pos);
4739 pos = message.length();
4741 return CTempString(message.c_str() + pos1, pos2 - pos1);
4746 "%00",
"%01",
"%02",
"%03",
"%04",
"%05",
"%06",
"%07",
4747 "%08",
"%09",
"%0A",
"%0B",
"%0C",
"%0D",
"%0E",
"%0F",
4748 "%10",
"%11",
"%12",
"%13",
"%14",
"%15",
"%16",
"%17",
4749 "%18",
"%19",
"%1A",
"%1B",
"%1C",
"%1D",
"%1E",
"%1F",
4750 "+",
"!",
"\"",
"#",
"$",
"%25",
"%26",
"'",
4751 "(",
")",
"*",
"%2B",
",",
"-",
".",
"/",
4752 "0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
4753 "8",
"9",
":",
";",
"<",
"%3D",
">",
"?",
4754 "@",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
4755 "H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
4756 "P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
4757 "X",
"Y",
"Z",
"[",
"\\",
"]",
"^",
"_",
4758 "`",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
4759 "h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
4760 "p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
4761 "x",
"y",
"z",
"{",
"|",
"}",
"~",
"%7F",
4762 "%80",
"%81",
"%82",
"%83",
"%84",
"%85",
"%86",
"%87",
4763 "%88",
"%89",
"%8A",
"%8B",
"%8C",
"%8D",
"%8E",
"%8F",
4764 "%90",
"%91",
"%92",
"%93",
"%94",
"%95",
"%96",
"%97",
4765 "%98",
"%99",
"%9A",
"%9B",
"%9C",
"%9D",
"%9E",
"%9F",
4766 "%A0",
"%A1",
"%A2",
"%A3",
"%A4",
"%A5",
"%A6",
"%A7",
4767 "%A8",
"%A9",
"%AA",
"%AB",
"%AC",
"%AD",
"%AE",
"%AF",
4768 "%B0",
"%B1",
"%B2",
"%B3",
"%B4",
"%B5",
"%B6",
"%B7",
4769 "%B8",
"%B9",
"%BA",
"%BB",
"%BC",
"%BD",
"%BE",
"%BF",
4770 "%C0",
"%C1",
"%C2",
"%C3",
"%C4",
"%C5",
"%C6",
"%C7",
4771 "%C8",
"%C9",
"%CA",
"%CB",
"%CC",
"%CD",
"%CE",
"%CF",
4772 "%D0",
"%D1",
"%D2",
"%D3",
"%D4",
"%D5",
"%D6",
"%D7",
4773 "%D8",
"%D9",
"%DA",
"%DB",
"%DC",
"%DD",
"%DE",
"%DF",
4774 "%E0",
"%E1",
"%E2",
"%E3",
"%E4",
"%E5",
"%E6",
"%E7",
4775 "%E8",
"%E9",
"%EA",
"%EB",
"%EC",
"%ED",
"%EE",
"%EF",
4776 "%F0",
"%F1",
"%F2",
"%F3",
"%F4",
"%F5",
"%F6",
"%F7",
4777 "%F8",
"%F9",
"%FA",
"%FB",
"%FC",
"%FD",
"%FE",
"%FF"
4799 size_t len =
str.length();
4802 "Empty name in extra-arg", 0);
4806 for (
size_t p = 0; p <
len; dst++) {
4811 "Inavild char in extra arg", p);
4815 if (n1 < 0 || n2 < 0) {
4817 "Inavild char in extra arg", p);
4819 str[dst] = char((n1 << 4) | n2);
4831 "Unencoded special char in extra arg", p);
4913 size_t sl_pos = message.find(
'/', pos);
4914 size_t sp_pos = message.find(
' ', pos);
4915 if (sl_pos < sp_pos) {
4939 static const char* s_TimeFormats[4] = {
4945 else if (
tmp.find(
'.') ==
NPOS) {
4979 bool have_severity =
false;
4980 size_t severity_pos = pos;
4982 if ( !
tmp.empty() ) {
4984 size_t sev_pos =
NPOS;
4985 if (
tmp.length() == 10 &&
tmp.find(
"Message[") == 0) {
4988 else if (
tmp.length() == 7 &&
tmp.find(
"Note[") == 0) {
4992 if (sev_pos !=
NPOS) {
4994 switch (
tmp[sev_pos] ) {
5017 have_severity =
true;
5024 if ( have_severity ) {
5025 pos = message.find_first_not_of(
' ', pos);
5027 pos = message.length();
5034 if (
tmp.empty() && severity_pos < message.length()) {
5036 pos = message.length();
5046 if (pos < message.length()) {
5048 pos = message.length();
5057 if (pos < message.length()) {
5059 pos = message.length();
5065 if (pos < message.length()) {
5068 size_t msg_end = message.find_first_not_of(
' ', pos);
5069 msg_end = message.find_first_of(
' ', msg_end);
5070 msg_end = message.find_first_not_of(
' ', msg_end);
5071 msg_end = message.find_first_of(
' ', msg_end);
5072 size_t extra_pos = message.find_first_not_of(
' ', msg_end);
5074 substr(0, msg_end - pos);
5079 pos = message.length();
5088 if (pos < message.length()) {
5099 size_t sep_pos = message.find(
" --- ", pos);
5102 if (pos < sep_pos && message[pos] !=
'"') {
5103 size_t mod_pos = pos;
5105 size_t lbr =
tmp.find(
"(");
5107 if (
tmp[
tmp.length() - 1] !=
')') {
5110 while (open_br > 0 && pos < message.length()) {
5111 if (message[pos] ==
'(') {
5114 else if (message[pos] ==
')') {
5119 if (message[pos] !=
' ' || pos >= message.length()) {
5124 pos = message.find_first_not_of(
' ', pos);
5126 pos = message.length();
5130 tmp =
tmp.substr(lbr + 1,
tmp.length() - lbr - 2);
5131 size_t dot_pos =
tmp.find(
'.');
5132 if (dot_pos !=
NPOS) {
5157 if (pos < sep_pos && message[pos] ==
'"') {
5163 if (
CTempString(message.c_str() + pos, 7) !=
", line ") {
5168 pos = message.find_first_not_of(
' ', pos);
5170 pos = message.length();
5174 if (pos < sep_pos) {
5176 if (message.find(
"::", pos) !=
NPOS) {
5177 size_t tmp_pos = sep_pos;
5178 while (tmp_pos > pos && message[tmp_pos - 1] ==
' ')
5180 tmp.assign(message.data() + pos, tmp_pos - pos);
5181 size_t dcol =
tmp.find(
"::");
5183 goto parse_unk_func;
5192 if (dcol <
tmp.length() - 2) {
5194 if (
tmp[
tmp.length() - 2] !=
'(' ||
tmp[
tmp.length() - 1] !=
')') {
5198 tmp.length() - dcol - 2);
5205 size_t unkf = message.find(
"UNK_FUNC", pos);
5212 if (
CTempString(message.c_str() + pos, 4) ==
"--- ") {
5236 string msg_str, line, last_msg_str;
5238 unique_ptr<SDiagMessage> msg;
5239 unique_ptr<SDiagMessage> last_msg;
5240 while (
in.good() ) {
5243 if (line.size() < 15) {
5244 if ( !line.empty() ) {
5245 msg_str +=
"\n" + line;
5251 for (
size_t i = 0;
i < 15;
i++) {
5252 if (line[
i] !=
'/' && (line[
i] <
'0' || line[
i] >
'9')) {
5254 msg_str +=
"\n" + line;
5259 if ( line.empty() ) {
5263 if ( msg_str.empty() ) {
5269 if ( last_msg.get() ) {
5272 last_msg_str = msg_str;
5273 last_msg.reset(msg.release());
5275 else if ( !last_msg_str.empty() ) {
5276 last_msg_str +=
"\n" + msg_str;
5280 Error <<
"Failed to parse message: " << last_msg_str);
5288 if ( !msg_str.empty() ) {
5291 if ( last_msg.get() ) {
5296 else if ( !last_msg_str.empty() ) {
5297 last_msg_str +=
"\n" + msg_str;
5304 Error <<
"Failed to parse message: " << last_msg_str);
5309 Error <<
"Failed to parse message: " << msg_str);
5325 return "request-start";
5327 return "request-stop";
5364 TDiagWriteFlags
flags)
const
5385 const char* mod_start = 0;
5386 const char* mod_end =
m_File;
5387 const char* c = strchr(
m_File, sep_chr);
5390 mod_start = mod_end;
5393 c = strchr(c + 1, sep_chr);
5398 while (*mod_start == sep_chr) {
5401 if (mod_end < mod_start + 1) {
5404 string ret(mod_start, mod_end - mod_start);
5424 static const char* s_BadSymbolPrefix =
"[INVALID_APPLOG_SYMBOL:";
5425 static const char* s_BadSymbolSuffix =
"]";
5426 static const size_t s_BadSymbolPrefixLen = strlen(s_BadSymbolPrefix);
5429 vector<CTempString> parts;
5430 parts.resize(src.
length() + 2);
5431 size_t part_idx = 0;
5432 const char* src_data = src.
data();
5434 size_t good_start = 0;
5435 size_t total_len = 0;
5436 for (
size_t pos = 0; pos < src.
size(); ++pos) {
5439 if (enc[0] == c && enc[1] == 0)
continue;
5442 if (good_start < pos) {
5444 good_part.
assign(src_data + good_start, pos - good_start);
5445 total_len += good_part.
size();
5448 if (warn_bad_name) {
5450 warn_part.
assign(s_BadSymbolPrefix, s_BadSymbolPrefixLen);
5451 total_len += s_BadSymbolPrefixLen;
5454 enc_part.
assign((c ==
' ' && warn_bad_name) ? s_EncodedSpace : enc);
5455 total_len += enc_part.
size();
5456 if (warn_bad_name) {
5458 warn2_part.
assign(s_BadSymbolSuffix, 1);
5461 good_start = pos + 1;
5463 if (part_idx + 3 >= parts.size()) parts.resize(parts.size() * 2);
5466 if (good_start < src.
size()) {
5468 good_part.
assign(src_data + good_start, src.
size() - good_start);
5469 total_len += good_part.
size();
5472 char*
buf =
new char[total_len];
5474 for (
size_t i = 0;
i < part_idx; ++
i) {
5476 strncpy(pos, part.
data(), part.
size());
5479 string ret(
buf, total_len);
5498 size_t p =
buf.find_first_of(
"\n\v\377");
5499 if (p ==
NPOS)
return;
5500 for (; p <
buf.size(); p++) {
5504 buf.insert(p, 1,
'\377');
5517 if (
buf.find_first_of(
"\v\377") ==
NPOS)
return;
5518 size_t src = 0, dst = 0;
5519 for (; src <
buf.size(); src++, dst++) {
5522 if (src <
buf.size() - 1 &&
5523 (
buf[src + 1] ==
'\377' ||
buf[src + 1] ==
'\v')) {
5563 string old_prefix =
trace.GetPrefix();
5564 trace.SetPrefix(
" ");
5565 os <<
"\n Stack trace:\n" <<
trace;
5566 trace.SetPrefix(old_prefix);
5591 const char* x_file =
m_File;
5593 for (
const char* s =
m_File; *s; s++) {
5594 if (*s ==
'/' || *s ==
'\\' || *s ==
':')
5598 os <<
'"' << x_file <<
'"';
5604 os << (print_file ?
", line " :
"line ") <<
m_Line;
5607 if (print_file || print_line)
5611 bool have_description =
false;
5623 have_description =
true;
5635 os <<
"Note[" << sev[0] <<
"]";
5657 bool print_location =
5663 bool need_separator =
false;
5664 if (print_location) {
5668 bool need_double_colon =
false;
5670 if ( have_module ) {
5672 need_double_colon =
true;
5676 if (need_double_colon)
5679 need_double_colon =
true;
5683 if (need_double_colon)
5685 need_double_colon =
false;
5689 if( need_double_colon )
5693 need_separator =
true;
5697 if (err_text_prefix && have_description &&
5700 os <<
"{" << description.
m_Message <<
"} ";
5701 need_separator =
true;
5704 if (need_separator) {
5717 if (have_description) {
5718 if (!err_text_prefix &&
5731 string buf = os.str();
5734 switch (s_DiagMergeLines->
Get()) {
5739 merge_lines =
false;
5771 bool have_description =
false;
5781 have_description =
true;
5789 os << setfill(
' ') << setw(13) << setiosflags(IOS_BASE::left)
5795 os << setfill(
' ') << setw(13)
5796 << setiosflags(IOS_BASE::left) << setw(0);
5798 os <<
"Note[" << sev[0] <<
"]:";
5803 os << resetiosflags(IOS_BASE::left);
5812 os << (have_module ?
x_GetModule() :
"UNK_MODULE");
5827 const char* x_file =
m_File;
5829 for (
const char* s =
m_File; *s; s++) {
5830 if (*s ==
'/' || *s ==
'\\' || *s ==
':')
5834 os <<
'"' << x_file <<
'"';
5837 os <<
"\"UNK_FILE\"";
5840 os <<
", line " <<
m_Line;
5884 if (have_description) {
5887 os <<
'\n' << description.
m_Message <<
' ';
5897 string buf = os.str();
5901 if (max_len > 0 &&
buf.size() > max_len) {
5902 buf.resize(max_len);
6037 new_flags |= prev_flags;
6103 buf.m_PostPrefix.erase();
6105 buf.m_PrefixList.clear();
6122 if ( !
buf.m_PrefixList.empty() ) {
6123 buf.m_PrefixList.pop_back();
6131 if (post_sev < eDiagSevMin || post_sev >
eDiagSevMax) {
6133 "SetDiagPostLevel() -- Severity must be in the range "
6134 "[eDiagSevMin..eDiagSevMax]");
6138 EDiagSev sev = CDiagBuffer::sm_PostSeverity;
6145 CDiagBuffer::sm_PostSeverity = post_sev;
6153 return CDiagBuffer::sm_PostSeverity;
6159 if (sev1 == sev2)
return 0;
6169 return CDiagBuffer::GetTraceEnabled();
6189 bool prev_status = (CDiagBuffer::sm_PostSeverityChange ==
eDiagSC_Enable);
6190 CDiagBuffer::sm_PostSeverityChange = disable_change ?
eDiagSC_Disable :
6198 if (die_sev < eDiagSevMin || die_sev >
eDiag_Fatal) {
6200 "SetDiagDieLevel() -- Severity must be in the range "
6201 "[eDiagSevMin..eDiag_Fatal]");
6205 EDiagSev sev = CDiagBuffer::sm_DieSeverity;
6206 CDiagBuffer::sm_DieSeverity = die_sev;
6213 return CDiagBuffer::sm_DieSeverity;
6220 bool retval = CDiagBuffer::sm_IgnoreToDie;
6221 CDiagBuffer::sm_IgnoreToDie = ignore;
6229 (void) CDiagBuffer::GetTraceEnabled();
6232 CDiagBuffer::sm_TraceDefault = dflt;
6235 how = CDiagBuffer::sm_TraceDefault;
6236 CDiagBuffer::sm_TraceEnabled = (how ==
eDT_Enable);
6242 return CDiagBuffer::GetTraceEnabled();
6279 stringstream str_os;
6282 string str = str_os.str();
6283 cerr.write(
str.data(),
str.size());
6292 bool report_switch =
ctx.IsSetOldPostFormat() &&
6294 string old_name, new_name;
6296 if ( CDiagBuffer::sm_Handler ) {
6297 old_name = CDiagBuffer::sm_Handler->
GetLogName();
6300 new_name =
handler->GetLogName();
6301 if (report_switch && new_name != old_name) {
6302 ctx.Extra().Print(
"switch_diag_to", new_name);
6307 if (CDiagBuffer::sm_CanDeleteHandler && CDiagBuffer::sm_Handler !=
handler)
6308 delete CDiagBuffer::sm_Handler;
6309 if ( TTeeToStderr::GetDefault() ) {
6314 CDiagBuffer::sm_Handler =
handler;
6315 CDiagBuffer::sm_CanDeleteHandler = can_delete;
6316 if (report_switch && !old_name.empty() && new_name != old_name) {
6317 ctx.Extra().Print(
"switch_diag_from", old_name);
6330 bool* current_ownership)
6333 if ( current_ownership ) {
6334 *current_ownership = CDiagBuffer::sm_CanDeleteHandler;
6336 if (take_ownership) {
6337 _ASSERT(CDiagBuffer::sm_CanDeleteHandler);
6338 CDiagBuffer::sm_CanDeleteHandler =
false;
6340 return CDiagBuffer::sm_Handler;
6367 stringstream str_os;
6369 string str = str_os.str();
6370 cerr.write(
str.data(),
str.size());
6377 string name =
typeid(*this).name();
6424 const string& stream_name)
6426 m_QuickFlush(quick_flush)
6428 if ( !stream_name.empty() ) {
6442 stringstream str_os;
6444 string str = str_os.str();
6457 #if defined(NCBI_OS_MSWIN)
6458 int mode = O_WRONLY | O_APPEND | O_CREAT | O_BINARY | O_NOINHERIT;
6460 int mode = O_WRONLY | O_APPEND | O_CREAT;
6475 #if defined(NCBI_OS_UNIX)
6493 m_LowDiskSpace(
false),
6544 if (limit > 0 && pos > limit) {
6597 if (it->m_PID != pid) {
6670 stringstream str_os;
6672 return str_os.str();
6721 || name ==
"/dev/null"
6722 || name ==
"/dev/stdout"
6723 || name ==
"/dev/stderr";
6763 if (!ptr || !(*ptr)) {
6805 *own_member =
false;
6812 if (member != &
m_Err) {
6817 if (member != &
m_Log) {
6863 unique_ptr<CStreamDiagHandler_Base>&
handler,
6866 if ( fname.empty() || fname ==
"/dev/null") {
6875 if ( !fh->Valid() ) {
6889 unique_ptr<CStreamDiagHandler_Base>
err_handler, log_handler,
6890 trace_handler, perf_handler;
6898 string ext = entry.
GetExt();
6899 if (ext ==
".log" ||
6906 string err_name = special ? adj_name : adj_name +
".err";
6907 string log_name = special ? adj_name : adj_name +
".log";
6908 string trace_name = special ? adj_name : adj_name +
".trace";
6909 string perf_name = special ? adj_name : adj_name +
".perf";
7182 virtual void*
Main(
void);
7190 #ifdef NCBI_HAVE_CONDITIONAL_VARIABLE
7206 DIAG_MAX_ASYNC_QUEUE_SIZE);
7210 : m_AsyncThread(
NULL)
7271 if (
thr->m_SubHandler->AllowAsyncWrite(mess)) {
7282 while (
Uint4(
thr->m_MsgsInQueue.Get()) >= s_MaxAsyncQueueSizeParam->
Get())
7284 ++
thr->m_CntWaiters;
7285 #ifdef NCBI_HAVE_CONDITIONAL_VARIABLE
7286 thr->m_DequeueCond.WaitForSignal(
thr->m_QueueLock);
7289 thr->m_QueueSem.Wait();
7292 --
thr->m_CntWaiters;
7294 thr->m_MsgQueue.push_back(async);
7295 if (
thr->m_MsgsInQueue.Add(1) == 1) {
7296 #ifdef NCBI_HAVE_CONDITIONAL_VARIABLE
7297 thr->m_QueueCond.SignalSome();
7299 thr->m_QueueSem.Post();
7305 thr->m_SubHandler->Post(mess);
7311 : m_NeedStop(
false),
7316 m_DequeueSem(0, 10000000),
7318 m_ThreadSuffix(thread_suffix)
7389 DIAG_ASYNC_BATCH_SIZE);
7402 const int batch_size =
NCBI_PARAM_TYPE(Diag, Async_Batch_Size)::GetDefault();
7406 for (
size_t i = 0;
i < buf_count; ++
i) {
7410 deque<SAsyncDiagMessage> save_msgs;
7417 #ifdef NCBI_HAVE_CONDITIONAL_VARIABLE
7429 int queue_counter = 0;
7430 while (!save_msgs.empty()) {
7432 save_msgs.pop_front();
7447 if ( !
buf->IsEmpty() ) {
7464 if (++queue_counter >= batch_size || save_msgs.empty()) {
7468 #ifdef NCBI_HAVE_CONDITIONAL_VARIABLE
7469 m_DequeueCond.SignalSome();
7478 for (
size_t i = 0;
i < buf_count; ++
i) {
7479 if ( !buffers[
i] ) {
7482 if ( !buffers[
i]->IsEmpty() ) {
7492 goto drain_messages;
7495 for (
size_t i = 0;
i < buf_count; ++
i) {
7496 if ( !buffers[
i] ) {
7499 if ( !buffers[
i]->IsEmpty() ) {
7514 #ifdef NCBI_HAVE_CONDITIONAL_VARIABLE
7515 m_QueueCond.SignalAll();
7523 <<
"Error while stopping thread for AsyncDiagHandler: " << ex);
7535 if ( !dir.empty() && !
CDir(dir).Exists() ) {
7547 "Failed to set log file for the selected event type: "
7548 "split log is disabled");
7574 bool old_ownership =
false;
7577 if ( !sub_handler ) {
7578 old_ownership =
false;
7584 if ( old_ownership ) {
7588 fhandler->SetSubHandler(sub_handler,
eDiagFile_All, old_ownership);
7598 if ( old_ownership ) {
7647 if ( CDiagBuffer::sm_CanDeleteErrCodeInfo &&
7648 CDiagBuffer::sm_ErrCodeInfo )
7649 delete CDiagBuffer::sm_ErrCodeInfo;
7650 CDiagBuffer::sm_ErrCodeInfo =
info;
7651 CDiagBuffer::sm_CanDeleteErrCodeInfo = can_delete;
7656 return (CDiagBuffer::sm_ErrCodeInfo != 0);
7662 if (take_ownership) {
7663 _ASSERT(CDiagBuffer::sm_CanDeleteErrCodeInfo);
7664 CDiagBuffer::sm_CanDeleteErrCodeInfo =
false;
7666 return CDiagBuffer::sm_ErrCodeInfo;
7714 m_PostFlags(ForceImportantFlags(post_flags)),
7715 m_OmitStackTrace(
false)
7726 m_PostFlags(ForceImportantFlags(post_flags)),
7727 m_OmitStackTrace(
false),
7793 if ( !stacktrace.
Empty() ) {
7808 string s = os.str();
7833 stack<const CException*> pile;
7841 main_pex = pile.top();
7843 *
this <<
"(" << main_pex->
GetType() <<
"::"
7848 *
this << main_pex->
GetType() <<
"::"
7852 for (; !pile.empty(); pile.pop()) {
7862 string err_type(pex->
GetType());
7869 pex_sev = collect_sev;
7873 pex_sev = print_sev;
7897 m_Buffer.PrintMessage(diagmsg, *
this);
7906 if (!str_sev || !*str_sev) {
7914 }
else if ( nsev == -1 ) {
7930 const char* message)
7939 const char* message)
7945 const char* expression,
7946 const char* message)
7949 "Assertion failed: (" <<
7950 (expression ? expression :
"") <<
") " <<
7951 (message ? message :
"") <<
Endm;
7957 const char* expression,
7958 const char* message)
7967 const char* message)
8000 buf.sm_CanDeleteHandler =
false;
8001 buf.sm_CanDeleteErrCodeInfo =
false;
8061 bool quick_flush =
true,
8063 void* cleanup_data = 0,
8087 const string& stream_name)
8089 string str_name = stream_name;
8090 if ( str_name.empty() ) {
8094 else if (os == &cout) {
8207 list<string> tokens;
8222 if (tokens.size() < 2) {
8223 ERR_POST_X(11,
"Error message file parsing: Incorrect file format "
8236 if ( !tokens.empty() ) {
8243 "Incorrect severity level in the verbose "
8264 bool err_ready =
false;
8266 int err_subcode = 0;
8269 int err_severity = -1;
8271 int err_subseverity = -1;
8281 if (err_ready &&
str[0] ==
'$') {
8282 if (err_subseverity == -1)
8283 err_subseverity = err_severity;
8288 err_subseverity = -1;
8296 err_message, err_ready))
8303 err_message, err_ready);
8305 }
else if (err_ready) {
8307 if (!err_text.empty()) {
8314 if (err_subseverity == -1)
8315 err_subseverity = err_severity;
8335 *description = entry;
const char * kWebDirToPort
const char * kToolkitRcPath
CAtomicCounter m_MsgsInQueue
CAsyncDiagThread(const string &thread_suffix)
deque< SAsyncDiagMessage > m_MsgQueue
virtual ~CAsyncDiagThread(void)
CDiagHandler * m_SubHandler
virtual void * Main(void)
Derived (user-created) class must provide a real thread function.
CCompatDiagHandler(FDiagHandler func, void *data, FDiagCleanup cleanup)
virtual void Post(const SDiagMessage &mess)
Post message to handler.
~CCompatDiagHandler(void)
~CCompatStreamDiagHandler(void)
CCompatStreamDiagHandler(CNcbiOstream *os, bool quick_flush=true, FDiagCleanup cleanup=0, void *cleanup_data=0, const string &stream_name=kEmptyStr)
Guard for collecting diag messages (affects the current thread only).
Incapsulate compile time information such as __FILE__, __LINE__, NCBI_MODULE, current function.
Thread local context data stored in TLS.
CDiagContextThreadData(const CDiagContextThreadData &)
CStopWatch * GetOrCreateStopWatch(void)
Get request timer, create if not exist yet.
CDiagCollectGuard * GetCollectGuard(void)
~CDiagContextThreadData(void)
TCount GetRequestId(void)
Request id.
TCollectGuards m_CollectGuards
void SetRequestId(TCount id)
CDiagContextThreadData(void)
TCount m_ThreadPostNumber
void CollectDiagMessage(const SDiagMessage &mess)
void AddCollectGuard(CDiagCollectGuard *guard)
SDiagMessage::TCount TCount
TTID GetTID(void) const
Get cached thread ID.
CRef< CRequestContext > m_DefaultRequestCtx
TCount GetThreadPostNumber(EPostNumberIncrement inc)
Get thread post number.
CStopWatch * GetStopWatch(void)
Get request timer or null.
static CDiagContextThreadData & GetThreadData(void)
Get diag context data for the current thread.
list< SDiagMessage > TDiagCollection
void SetRequestContext(CRequestContext *ctx)
Set request context.
size_t m_DiagCollectionSize
CRequestContext & GetRequestContext(void)
Get current request context.
CRef< CRequestContext > m_RequestCtx
void ResetStopWatch(void)
Delete request timer.
CDiagBuffer & GetDiagBuffer(void)
Diag buffer.
CDiagContextThreadData & operator=(const CDiagContextThreadData &)
unique_ptr< CDiagBuffer > m_DiagBuffer
list< CDiagCollectGuard * > TCollectGuards
void RemoveCollectGuard(CDiagCollectGuard *guard)
TDiagCollection m_DiagCollection
CDiagFileHandleHolder(const string &fname, CDiagHandler::TReopenFlags flags)
virtual ~CDiagFileHandleHolder(void)
CDiagLock(ELockType locktype)
CFileHandleDiagHandler –.
void Guard(resource_type &resource)
Manually force the guard to protect some other resource.
void Release()
Manually force the resource to be released.
CLogRateLimit(TValue val)
static CNcbiApplication * Instance(void)
Singleton method.
CNcbiOstrstreamToString class helps convert CNcbiOstrstream to a string Sample usage:
CRecursionGuard(bool &flag)
T & Get(void)
Create the variable if not created yet, return the reference.
Helper class to hold hit id and sub-hit counter which can be shared between multiple request contexts...
bool Empty(void) const
Check if stack trace information is available.
void SetPrefix(const string &prefix) const
Set new prefix.
CStreamDiagHandler_Base –.
Template for parsing string into pairs of name and value or merging them back into a single string.
static string GetUserName(void)
Get actual user name for the current process.
AutoPtr< CDiagHandler > m_OrigHandler
virtual void PostToConsole(const SDiagMessage &mess)
Post message to console regardless of its severity.
CDiagHandler * GetOriginalHandler(void) const
virtual void Post(const SDiagMessage &mess)
Post message to handler.
virtual void Reopen(TReopenFlags flags)
Reopen file to enable log rotation.
virtual string GetLogName(void)
Get current diag posts destination.
CTeeDiagHandler(CDiagHandler *orig, bool own_orig)
CTempString implements a light-weight string on top of a storage buffer whose lifetime management is ...
Callback interface for stream parser.
Encoder interface. Names and values can be encoded with different rules.
container_type::const_iterator const_iterator
container_type::iterator iterator
const_iterator end() const
const_iterator find(const key_type &key) const
void(*)(CSeq_entry_Handle seh, IWorkbench *wb, const CSerialObject &obj) handler
void Print(const CCompactSAMApplication::AlignInfo &ai)
Define CVersionInfo, a version info storage class.
std::ofstream out("events_result.xml")
main entry point for tests
static void cleanup(void)
static int err_handler(DBPROCESS *dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr)
static const char * str(char *buf, int n)
void reset(element_type *p=0, EOwnership ownership=eTakeOwnership)
Reset will delete the old pointer (if owned), set content to the new value, and assume the ownership ...
static string GetAppName(EAppNameType name_type=eBaseName, int argc=0, const char *const *argv=NULL)
const CNcbiEnvironment & GetEnvironment(void) const
Get the application's cached environment.
const string & GetProgramExecutablePath(EFollowLinks follow_links=eIgnoreLinks) const
Get the application's executable path.
static CNcbiApplicationGuard InstanceGuard(void)
Singleton method.
const CNcbiRegistry & GetConfig(void) const
Get the application's cached configuration parameters (read-only).
#define ITERATE(Type, Var, Cont)
ITERATE macro to sequence through container elements.
element_type * get(void) const
Get pointer.
const string & GetProgramDisplayName(void) const
Get the application's "display" name.
#define NON_CONST_ITERATE(Type, Var, Cont)
Non constant version of ITERATE macro.
const CVersionAPI & GetFullVersion(void) const
Get the program version information.
@ eTakeOwnership
An object can take ownership of another.
@ eNoOwnership
No ownership is assumed.
void Set(TValue new_value) THROWS_NONE
Set atomic counter value.
TValue Add(int delta) THROWS_NONE
Atomically add value (=delta), and return new counter value.
TValue Get(void) const THROWS_NONE
Get atomic counter value.
#define _TRACE_X(err_subcode, message)
EValidateAction xncbi_GetValidateAction(void)
Get the action to be performed.
@ eValidate_Throw
Throw an exception if not valid.
bool x_IsSetOldFormat(void) const
int m_ErrSubCode
Sub Error code.
TDiagPostFlags GetPostFlags(void) const
Get post flags for the current message.
virtual ~CAsyncDiagHandler(void)
string m_Explanation
Error message (with detailed explanation)
void Write(string &str, TDiagWriteFlags flags=fNone) const
Binary OR of "EDiagWriteFlags".
void Release(void)
Release the guard.
void SetDiagFilter(EDiagFilter what, const char *filter_str)
Set diagnostic filter.
TExtraArgs m_ExtraArgs
If event type is "extra", contains the list of arguments.
void PushDiagPostPrefix(const char *prefix)
Push a string to the list of message prefixes.
static string SelectLastHitID(const string &hit_ids)
Select the last hit id from the list of ids separated with commas and optional spaces.
void SetAutoWrite(bool value)
Set AutoWrite flag.
void PrintRequestStop(void)
Print request stop message (for request-driven applications)
CDiagContext_Extra & Print(const string &name, const string &value)
The method does not print the argument, but adds it to the string.
void UnsetRequestStatus(void)
CDiagContext_Extra PrintRequestStart(void)
Create a temporary CDiagContext_Extra object.
CDiagContext_Extra & AllowBadSymbolsInArgNames(void)
Allow bad symbols in argument names.
void x_InitData(void) const
void ParseCurrFunctName(void) const
void SetCollectSeverity(EDiagSev sev)
Set new collect severity.
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.
string GetSessionID(void) const
Get the effective session id: the per-request session id if set, or the default session id.
TCount m_RequestId
FastCGI iteration or request ID.
EDiagPostFlag
Which parts of the diagnostic context should be posted.
void SetBytesWr(Int8 bytes)
EDiagSev GetDiagPostLevel(void)
Get current threshold severity for posting the messages.
~CDiagCollectGuard(void)
Destroy the guard, return post level to the one set before the guard initialization.
void SetDiagPostFlag(EDiagPostFlag flag)
Set the specified flag (globally).
static const char * kProperty_UserName
Global properties.
EDiagSevChange
Severity level change state.
bool m_AllowBadExtraNames
static string GetEventName(EEventType event)
unique_ptr< CEncodedString > m_Username
CStreamDiagHandler_Base * m_Perf
bool ParseMessage(const string &message)
Parse the whole string into the message.
string m_StrCurrFunctName
static bool IsSetOldPostFormat(void)
Check old/new format flag (for compatibility only)
#define ERR_POST_ONCE(message)
Error posting only once during program execution.
const char * m_File
File name.
EDiagSev m_PostSeverity
Post severity.
Uint8 TCount
Generic type for counters (posts, requests etc.)
const char * m_Buffer
Not guaranteed to be '\0'-terminated!
void SetModule(const string &module)
void PrintStart(const string &message)
Print start/stop etc.
const string & GetHost(void) const
Get host name.
static void s_UnescapeNewlines(string &buf)
CStreamDiagHandler_Base * m_Trace
const CNcbiDiag & SetClass(const char *nclass) const
Set class name.
CNcbiOstream * m_Stream
Diagnostic stream.
const string & GetEncodedHostname(void) const
Get URL-encoded hostname.
EDiagAppState GetGlobalAppState(void) const
Always returns global application state.
string GetEncodedSessionID(void) const
Get url-encoded session id.
string GetStringUID(TUID uid=0) const
Return string representation of UID.
CDiagContext & GetDiagContext(void)
Get diag context instance.
void(* FAbortHandler)(void)
Abort handler function type.
void SetAppState(EDiagAppState state)
bool GetAutoIncRequestIDOnPost(void) const
Get auto-increment state.
bool x_ParseExtraArgs(const string &str, size_t pos)
static void SetRequestContext(CRequestContext *ctx)
Shortcut to CDiagContextThreadData::GetThreadData().SetRequestContext()
virtual void Reopen(TReopenFlags flags)
Reopen file to enable log rotation.
void SetAppState(EDiagAppState state)
Set application state.
void x_Match(const string &name, const string &value, CDiagContext_Extra &extra) const
void SetDiagFixedPostLevel(const EDiagSev post_sev)
Sets and locks the level, combining the previous two calls.
CNcbiOstream * GetLogStream(EDiagFileType file_type)
Get current log stream.
void SetAction(EAction action)
Specify on-destroy action.
void SetPrintSeverity(EDiagSev sev)
Set new print severity.
Uint8 GetStartingPoint(void) const
Get the lowest thread-local post number in this guard's scope.
void SetSplitLogFile(bool value)
Split log files flag.
virtual void WriteMessage(const char *buf, size_t len, EDiagFileType file_type)
Write string to the log.
EDiagCollectMessages
Flags to control collecting messages and flushing them to the new destination when switching diag han...
static bool UpdatePID(void)
Reset PID cache (e.g. after fork). Return true if PID was updated.
const char * m_Module
Module name.
static const char * kProperty_AppName
virtual void Reopen(TReopenFlags flags)
Reopen file to enable log rotation.
virtual string ComposeMessage(const SDiagMessage &msg, EDiagFileType *file_type) const
Compose message without writing it.
CStreamDiagHandler_Base(void)
static const char * kProperty_ClientIP
CDiagContext_Extra & PrintNcbiRoleAndLocation(void)
const string & GetHost(void) const
Access to strings stored in SDiagMessageData.
static bool sm_ApplogSeverityLocked
bool m_TraceEnabled
Trace enabled?
~CDiagRestorer(void)
Restores captured settings.
string GetSessionID(void) const
Session ID.
const string & GetHostname(void) const
Get cached hostname - do not try to detect host name as GetHost() does.
void DiagHandler_Reopen(void)
Ask diagnostic handler to reopen log files if necessary.
string GetDiagFilter(EDiagFilter what)
Get current diagnostic filter.
virtual void PostToConsole(const SDiagMessage &mess)
Post message to console regardless of its severity.
int GetExitSignal(void) const
Get exit signal.
void SetLogRate_Limit(ELogRate_Type type, unsigned int limit)
virtual void Reopen(TReopenFlags)
Reopen file to enable log rotation.
unique_ptr< CRequestRateControl > m_TraceLogRC
string GetLogFile(EDiagFileType file_type) const
Get current log file name.
void SetRequestID(TCount rid)
Set request ID.
CAsyncDiagThread * m_AsyncThread
Thread handling all physical printing of log messages.
void SetSessionID(const string &session)
SDiagMessage(EDiagSev severity, const char *buf, size_t len, const char *file=0, size_t line=0, TDiagPostFlags flags=eDPF_Default, const char *prefix=0, int err_code=0, int err_subcode=0, const char *err_text=0, const char *module=0, const char *nclass=0, const char *function=0)
Initialize SDiagMessage fields.
atomic< bool > m_ErrLogSuspended
CDiagContext_Extra Extra(void) const
Create a temporary CDiagContext_Extra object.
#define DIAG_COMPILE_INFO
Make compile time diagnostic information object to use in CNcbiDiag and CException.
list< SDiagMessage > TMessages
TCount m_ProcPost
Number of the post in the process.
bool DisableDiagPostLevelChange(bool disable_change)
Disable change the diagnostic post level.
void x_CreateUID_AsyncSafe(void) const
bool IsSetRequestStatus(void) const
void SetSubHandler(CStreamDiagHandler_Base *handler, EDiagFileType file_type, bool own)
size_t m_Line
Line number in file.
void SetLogName(const string &log_name)
void SetHostname(const string &hostname)
Set hostname.
void SetDiagRequestId(Uint8 id)
Set iteration number/request ID.
TUID GetUID(void) const
Return (create if not created yet) unique diagnostic ID.
CDiagBuffer & m_Buffer
This thread's error msg. buffer.
TUID GetUID(void) const
Get UID from current context or parsed from a string.
#define ERR_POST_X_ONCE(err_subcode, message)
Error posting only once during program execution with default error code and given error subcode.
void SetClientIP(const string &client)
static const char * kProperty_ExitSig
bool CheckFilters(const CException *ex=NULL) const
Check if filters are passed for the current message.
void x_Init(EDiagSev print_severity, EDiagSev collect_severity, EAction action)
bool m_CanDeleteErrCodeInfo
Can delete err code info?
virtual void SetLogName(const string &log_name)
void x_SaveContextData(void) const
int TDiagPostFlags
Binary OR of "EDiagPostFlag".
string x_GetNextHitID(bool is_default) const
string FormatExtraMessage(void) const
Convert extra arguments to string.
EDiagSev m_Severity
Severity level.
static void x_StartRequest(void)
bool GetSplitLogFile(void)
Get split log files flag.
~CNcbiDiag(void)
Destructor.
bool m_QuickFlush
Quick flush of stream flag.
unique_ptr< TMessages > m_Messages
bool GetOmitStackTrace(void) const
static string SelectLastSessionID(const string &session_ids)
Select the last session id from the list of ids separated with commas and optional spaces,...
unique_ptr< CEncodedString > m_Host
EAppDiagStream
Where to write the application's diagnostics to.
EDiagTrace m_TraceDefault
Default trace setting.
Uint8 TTID
Get thread ID used in messages.
void PrintExtra(const string &message)
Print extra message in plain text format.
static bool UpdatePID_AsyncSafe(void)
bool x_IsSetDefaultHitID(void) const
void UnsetDiagTraceFlag(EDiagPostFlag flag)
virtual string ComposeMessage(const SDiagMessage &msg, EDiagFileType *file_type) const
Compose message without writing it.
EPostNumberIncrement
Post number increment flag for GetProcessPostNumber() and GetThreadPostNumber().
const char * m_Prefix
Prefix string.
virtual void Post(const SDiagMessage &mess)=0
Post message to handler.
bool x_DiagAtApplicationLevel(void) const
string GetDefaultHitID(void) const
Get global default hit id.
EDiagSev GetDiagDieLevel(void)
Get the "die" (abort) level for the program.
static void s_EscapeNewlines(string &buf)
bool GetDescription(const ErrCode &err_code, SDiagErrCodeDescription *description) const
Get description for specified error code.
void DeleteProperty(const string &name, EPropertyMode mode=eProp_Default)
Delete a property by name.
string m_Message
Error message (short)
~CDiagContext_Extra(void)
Prints all arguments as "name1=value1&name2=value2...".
#define DIAG_POST_LEVEL
Diagnostic post severity level.
CDiagContext_Extra & operator=(const CDiagContext_Extra &args)
virtual string ComposeMessage(const SDiagMessage &msg, EDiagFileType *file_type) const
Compose message without writing it.
void PushMessage(const SDiagMessage &message)
Save new message.
bool IsDiagStream(const CNcbiOstream *os)
size_t GetLine(void) const
Get line number for the current message.
const string & GetEncodedAppName(void) const
Get URL-encoded application name.
SDiagErrCodeDescription(void)
Constructor.
bool IsVisibleDiagPostLevel(EDiagSev sev)
Check if the specified severity is higher or equal to the currently selected post level and will be p...
EEventType
Type of event to report.
void FlushMessages(CDiagHandler &handler)
Flush the collected messages to the current diag handler.
TDiagPostFlags m_Flags
Bitwise OR of "EDiagPostFlag".
bool m_NoTee
Special flag indicating that the message should not be printed by Tee-handler.
static CDiagContext * sm_Instance
EDiagSev m_DieSeverity
Die level severity.
static CRequestContext & GetRequestContext(void)
Shortcut to CDiagContextThreadData::GetThreadData().GetRequestContext()
atomic< bool > m_AppLogSuspended
TCount GetRequestID(void) const
Get request ID (or zero if not set).
void PopDiagPostPrefix(void)
Pop a string from the list of message prefixes.
void AppendDiagFilter(EDiagFilter what, const char *filter_str)
Append diagnostic filter.
static void DiagTrouble(const CDiagCompileInfo &info, const char *message=NULL)
Display trouble error message.
void SetAppName(const string &app_name)
Set application name.
static const char * kProperty_ReqTime
bool GetDiagTrace(void)
Check if traces are enabled.
void DiscardMessages(void)
Discard the collected messages without printing them.
string GetClientIP(void) const
Client IP/hostname.
static TCount GetThreadPostNumber(EPostNumberIncrement inc)
Return thread post number (incrementing depends on the flag).
CStopWatch * m_ReopenTimer
static bool GetLogTruncate(void)
Get log file truncation flag.
static void SetApplogSeverityLocked(bool lock)
static TPID GetPID(void)
Get cached PID (read real PID if not cached yet).
CNcbiOstream & x_NewWrite(CNcbiOstream &os, TDiagWriteFlags fl=fNone) const
const CNcbiDiag & SetFile(const char *file) const
Set file name to post.
void x_LogHitID(void) const
CNcbiDiag(EDiagSev sev=eDiag_Error, TDiagPostFlags post_flags=eDPF_Default)
Constructor.
void x_CreateUID(void) const
CStopWatch * m_ReopenTimer
CStreamDiagHandler_Base * m_Log
CDiagRestorer(void)
Captures current settings.
const string & GetHostIP(void) const
Get host IP address.
TCount m_ThrPost
Number of the post in the thread.
EDiagSevChange m_PostSeverityChange
Severity change.
int m_Severity
Message severity (if less that 0, then use current diagnostic severity level)
void SetHostIP(const string &ip)
Set host IP address.
int CompareDiagPostLevel(EDiagSev sev1, EDiagSev sev2)
Compare two severities.
static void x_LogEnvironment(void)
static const char * kProperty_ExitCode
void UnsetDiagPostFlag(EDiagPostFlag flag)
Unset the specified flag (globally).
unique_ptr< CStopWatch > m_StopWatch
string GetClient(void) const
CDiagHandler * GetDiagHandler(bool take_ownership, bool *current_ownership)
Get the currently set diagnostic handler class.
void SetDiagPostPrefix(const char *prefix)
Specify a string to prefix all subsequent error postings with.
void SetDoubleDiagHandler(void)
Output diagnostics using both old and new style handlers.
CDiagContext_Extra & PrintNcbiAppInfoOnRequest(void)
static string GetDefaultClientIP(void)
Get default client ip.
const string & GetAppName(void) const
CStreamDiagHandler(CNcbiOstream *os, bool quick_flush=true, const string &stream_name="")
Constructor.
void RemoveFromDiag(void)
Remove this DiagHandler from diagnostics.
void SetAutoIncRequestIDOnPost(bool enable)
Auto-increment request ID with every posted message.
EDiagSev SetDiagDieLevel(EDiagSev die_sev)
Set the "die" (abort) level for the program.
void SetRequestStatus(int status)
void Abort(void)
Smart abort function.
string x_GetModule(void) const
bool IsSetHitID(EHitIDSource src=eHitID_Any) const
Check if there's an explicit hit id or the default one.
const CNcbiDiag & SetFunction(const char *function) const
Set function name.
static void DiagValidate(const CDiagCompileInfo &info, const char *expression, const char *message)
Display validation message.
list< TExtraArg > TExtraArgs
size_t m_BufferLen
Length of m_Buffer.
static const char * kProperty_HostName
void SetDiagErrCodeInfo(CDiagErrCodeInfo *info, bool can_delete)
Set handler for processing error codes.
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.
static bool GetDefaultAutoIncRequestIDOnPost(void)
Get default auto-increment flag.
static TDiagPostFlags ForceImportantFlags(TDiagPostFlags flags)
Set important flags to their globally set values.
static const char * SeverityName(EDiagSev sev)
Get a common symbolic name for the severity levels.
EDiagSev SetDiagPostLevel(EDiagSev post_sev)
Set the threshold severity for posting the messages.
EDiagTrace
Which setting disables/enables posting of "eDiag_Trace" messages.
EAction
Action to perform in guard's destructor.
ELogRate_Type
Type of logging rate limit.
void SetExitCode(int exit_code)
Set exit code.
CDiagFileHandleHolder * m_Handle
#define ERR_POST_X(err_subcode, message)
Error posting with default error code and given error subcode.
const string & GetEncodedHost(void) const
URL-encoded version of GetHost()
bool x_LogHitIDOnError(void) const
const CStopWatch & GetRequestTimer(void) const
Request execution timer.
void(* FDiagHandler)(const SDiagMessage &mess)
Diagnostic handler function type.
void SetExitSignal(int exit_sig)
Set exit signal.
SDiagMessage::EEventType m_EventType
const char * m_Class
Class name.
deque< SDiagMessage > TMessages
Save messages if the handle is unavailable.
unsigned int GetLogRate_Period(ELogRate_Type type) const
Logging rate control - the messages control period, seconds.
void WriteStdPrefix(CNcbiOstream &ostr, const SDiagMessage &msg) const
Write standard prefix to the stream.
bool GetReadOnly(void) const
Get current read-only flag.
EDiagSev GetSeverityCap(void) const
Get current severity cap for use in ePrintCapped mode.
string GetNextHitID(void) const
Create global unique request id.
TDiagPostFlags m_PostFlags
Post flags.
pair< string, string > TExtraArg
static NCBI_XNCBI_EXPORT void DiagAssert(const CDiagCompileInfo &info, const char *expression, const char *message=NULL)
Assert specified expression and report results.
static const char * kProperty_BytesRd
void InstallToDiag(void)
Install this DiagHandler into diagnostics.
void SetProperty(const string &name, const string &value, EPropertyMode mode=eProp_Default)
Set application context property by name.
CFileHandleDiagHandler(const string &fname, EDiagFileType file_type=eDiagFile_All)
Constructor.
EDiagSev GetCollectSeverity(void) const
Get current collect severity.
SDiagMessage::TCount TCount
~CFileHandleDiagHandler(void)
Close file handle.
static bool IsUsingRootLog(void)
Check if the current diagnostics destination is /log/*.
void Flush(void)
Print the message and reset object.
bool IsSetDiagPostFlag(EDiagPostFlag flag, TDiagPostFlags flags=eDPF_Default)
Check if a specified flag is set.
SDiagMessage & operator=(const SDiagMessage &message)
Assignment of messages.
CDiagContext_Extra(const CDiagContext_Extra &args)
Copying the object will prevent printing it on destruction.
void SetLogRate_Period(ELogRate_Type type, unsigned int period)
void PrintProperties(void)
Forced dump of all set properties.
static bool IsUsingSystemThreadId(void)
Check if system TID is printed instead of CThread::GetSelf()
TInfo m_Info
Map storing error codes and descriptions.
CDiagAutoPrefix(const string &prefix)
Constructor.
void SetBytesRd(Int8 bytes)
CStreamDiagHandler_Base * x_GetHandler(EDiagFileType file_type) const
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.
CSharedHitId x_GetDefaultHitID(EDefaultHitIDFlags flag) const
static const string & GetHostLocation(void)
Get host location (be-md/st-va) from /etc/ncbi/location.
EDiagFileType
CDiagHandler –.
EDiagAppState
Application execution states shown in the std prefix.
friend const CNcbiDiag & Endm(const CNcbiDiag &diag)
Flush current message, start new one.
void(* FDiagCleanup)(void *data)
Diagnostic cleanup function type.
CDiagCompileInfo m_CompileInfo
list< string > m_PrefixList
List of prefixes.
static const string & GetHostRole(void)
Get host role (DEV/QA/TRY/PROD) from /etc/ncbi/role.
static void SetDefaultClientIP(const string &client_ip)
Set new default client ip.
CDiagContext_Extra & PrintNcbiAppInfoOnStart(void)
virtual void SetLogName(const string &log_name)
static void x_FinalizeSetupDiag(void)
Internal function, should be used only by CNcbiApplication.
bool SetLogFile(const string &file_name, EDiagFileType file_type, bool quick_flush)
Set new log file.
static void UpdateOnFork(TOnForkFlags flags)
Update diagnostics after fork().
CDiagContext_Extra & SetType(const string &type)
Set extra message type.
bool ApproveMessage(SDiagMessage &msg, bool *show_warning)
CStreamDiagHandler_Base * m_Err
bool m_ApplogSeverityLocked
Limiting applog post level?
~CDiagAutoPrefix(void)
Remove the prefix automagically, when the object gets out of scope.
TDiagPostFlags SetDiagTraceAllFlags(TDiagPostFlags flags)
Versions of the above for extra trace flags.
const CNcbiDiag & x_Put(const CException &ex) const
Helper func for the exception-related Put()
string GetProperty(const string &name, EPropertyMode mode=eProp_Default) const
Get application context property by name, return empty string if the property is not set.
static void SetupDiag(EAppDiagStream ds=eDS_Default, CNcbiRegistry *config=NULL, EDiagCollectMessages collect=eDCM_NoChange, const char *cmd_logfile=NULL)
Application-wide diagnostics setup.
virtual void WriteMessage(const char *buf, size_t len, EDiagFileType file_type)
Write string to the log.
bool SetLogFile(const string &file_name, EDiagFileType file_type, bool quick_flush)
Set log files.
static const char * kProperty_SessionID
EDiagAppState GetAppState(void) const
Return application state for the current thread if it's set.
void InitMessages(size_t max_size=100)
Start collecting all messages (the collected messages can be flushed to a new destination later).
bool IsSetDiagHandler(void)
Check if diagnostic handler is set.
static void UseSystemThreadId(bool value=true)
Switch printing system TID (rather than CThread::GetSelf()) on/off.
static void SetUseRootLog(void)
@depracated The flag is always set now, the funcion still calls SetupDiag() for compatibility,...
string GetHitID(void) const
Get explicit hit id or the default one (from HTTP_NCBI_PHID etc).
bool Read(const string &file_name)
Read error description from specified file.
unique_ptr< CSharedHitId > m_DefaultHitId
static const char * kLogName_Syslog
virtual string GetLogName(void)
Get current diag posts destination.
const char * m_Function
Function name.
static bool IsMainThreadDataInitialized(void)
#define ERR_POST(message)
Error posting with file, line number information but without error codes.
CNcbiOstream & x_OldWrite(CNcbiOstream &os, TDiagWriteFlags fl=fNone) const
virtual string GetLogName(void)
Get current diag posts destination.
void SetDiagHandler(CDiagHandler *handler, bool can_delete)
Set the diagnostic handler using the specified diagnostic handler class.
TUID UpdateUID(TUID uid=0) const
Take the source UID and replace its timestamp part with the current time.
virtual void Reopen(TReopenFlags flags)
Reopen file to enable log rotation.
void SetDefaultHitID(const string &hit_id)
Set new global default hit id.
CDiagCollectGuard(void)
Set collectable severity and optionally applied print-severity cap to the current post level,...
SDiagMessage::TExtraArgs TExtraArgs
const char * m_ErrText
Sometimes 'error' has no numeric code, but can be represented as text.
bool IsSetExplicitSessionID(void) const
Does not check default SID.
atomic< bool > m_TraceLogSuspended
static void sx_ThreadDataTlsCleanup(CDiagContextThreadData *value, void *cleanup_data)
void SetDiagTrace(EDiagTrace how, EDiagTrace dflt)
Set the diagnostic trace settings.
EDiagAppState GetAppState(void) const
const string & GetAppName(void) const
Get application name.
const char * GetClass(void) const
Get class name of the current message.
CDiagHandler * m_Handler
Class handler.
void x_PrintMessage(SDiagMessage::EEventType event, const string &message)
EDiagSev
Severity level for the posted diagnostics.
const char * g_DiagUnknownFunction(void)
static void SetOldPostFormat(bool value)
Set old/new format flag.
void SetDefaultSessionID(const string &session_id)
Set new default session id.
EEventType m_Event
If the severity is eDPF_AppLog, m_Event contains event type.
TDiagPostFlags SetDiagPostAllFlags(TDiagPostFlags flags)
Set global post flags to "flags".
void SetCustomThreadSuffix(const string &suffix)
Set custom suffix to use on all threads in the server's pool.
bool x_NeedModule(void) const
void SetFunction(const string &func)
Uint8 GetDiagRequestId(void)
Get iteration number/request ID.
const char * GetFile(void) const
Get file used for the current message.
bool m_IgnoreToDie
Ignore to die on die sev.
static void SetLogTruncate(bool value)
Set log file truncation flag.
SDiagMessage::TExtraArg TExtraArg
CNcbiOstream * GetDiagStream(void)
Get current diagnostic stream (if it was set by SetDiagStream) or NULL.
unique_ptr< TMessages > m_Messages
void PrintStop(void)
Print exit message.
static NCBI_XNCBI_EXPORT void DiagFatal(const CDiagCompileInfo &info, const char *message)
Display fatal error message.
void SetUsername(const string &username)
Set username.
bool IsSetDiagErrCodeInfo(void)
Indicates whether an error-code processing handler has been set.
CDiagErrCodeInfo * m_ErrCodeInfo
Error code information.
unique_ptr< CRequestRateControl > m_AppLogRC
const string & GetHitId(void) const
Get hit id value.
static const char * kProperty_HostIP
const char * m_CurrFunctName
CFileDiagHandler(void)
Constructor.
EDiagFileType x_GetDiagFileType(const SDiagMessage &msg) const
#define DIAG_TRACE
Diagnostic trace setting.
static bool StrToSeverityLevel(const char *str_sev, EDiagSev &sev)
Get severity from string.
EPropertyMode
Property visibility flag.
EDiagSev GetPrintSeverity(void) const
Get current print severity.
string GetDefaultSessionID(void) const
Get default session id.
virtual void Post(const SDiagMessage &mess)
Post message to the handler.
static const char * kProperty_AppState
Per-thread properties.
int GetExitCode(void) const
Get exit code.
void SetOwnership(CStreamDiagHandler_Base *handler, bool own)
Change ownership for the given handler if it's currently installed.
virtual bool AllowAsyncWrite(const SDiagMessage &msg) const
Check if the handler supports async writes.
void SetFile(const string &file)
void SetClass(const string &cls)
void SetDiagTraceFlag(EDiagPostFlag flag)
void x_ResetHandler(CStreamDiagHandler_Base **ptr, bool *owned)
CTime GetTime(void) const
Get time and date - current or parsed.
void x_LogHitID_WithLock(void) const
CDiagErrCodeInfo * GetDiagErrCodeInfo(bool take_ownership)
Get handler for processing error codes.
virtual void Post(const SDiagMessage &mess)
Post message to the handler.
virtual void Post(const SDiagMessage &mess)
Post message to the handler.
virtual string GetLogName(void)
Get current diag posts destination.
friend class CDiagContext_Extra
static bool IsApplogSeverityLocked(void)
When using applog, the diag post level is locked to Warning.
unique_ptr< CEncodedString > m_DefaultSessionId
string GetLogFile(EDiagFileType file_type)
Get log file name for the given log type.
static const char * kProperty_BytesWr
void SetDiagStream(CNcbiOstream *os, bool quick_flush, FDiagCleanup cleanup, void *cleanup_data, const string &stream_name)
Set diagnostic stream.
unique_ptr< CEncodedString > m_AppName
void SetAbortHandler(FAbortHandler func)
Set/unset abort handler.
CNcbiLogFields(const string &source)
Load fields to be logged from NCBI_LOG_FIELDS environment variable.
CDiagCompileInfo(void)
CDiagCompileInfo::
virtual void Post(const SDiagMessage &mess)
Implementation of CDiagHandler.
EDiagFilter
Diag severity types to put the filter on.
EDiagSev GetSeverity(void) const
Get severity of the current message.
EAction GetAction(void) const
Get selected on-destroy action.
static void ParseDiagStream(CNcbiIstream &in, INextDiagMessage &func)
Stream parser.
void x_SetHandler(CStreamDiagHandler_Base **member, bool *own_member, CStreamDiagHandler_Base *handler, bool own)
unsigned int GetLogRate_Limit(ELogRate_Type type) const
Logging rate control - max number of messages per period.
bool m_TypedExtra
Set to true if this is a typed extra message (the arguments include "NCBIEXTRATYPE=<extra-type>").
virtual void WriteMessage(const char *buf, size_t len, EDiagFileType file_type)
Write string to the log.
static TCount GetProcessPostNumber(EPostNumberIncrement inc)
Return process post number (incrementing depends on the flag).
static const char * kProperty_ReqStatus
string GetEncodedSessionID(void) const
Get URL-encoded session ID.
void g_Diag_Use_RWLock(bool enable)
Use RW-lock for synchronization rather than mutex.
void SetGlobalAppState(EDiagAppState state)
Set global application state.
bool m_CanDeleteHandler
Can handler be deleted?
EDiagAppState GetAppState(void) const
Application state.
const CNcbiDiag & SetModule(const char *module) const
Set module name.
unique_ptr< CRequestRateControl > m_ErrLogRC
virtual bool AllowAsyncWrite(const SDiagMessage &msg) const
Check if the handler supports async writes.
virtual bool AllowAsyncWrite(const SDiagMessage &msg) const
Check if the handler supports async writes.
SDiagMessageData * m_Data
virtual CNcbiOstream * GetStream(void)
const string & GetUsername(void) const
Get username.
bool IgnoreDiagDieLevel(bool ignore)
Ignore the die level settings.
string GetSession(void) const
@ fResetOnStart
Reset values when printing request-start.
@ fTruncate
Truncate file to zero size.
@ fDefault
Default reopen flags:
@ fCheck
Reopen only if necessary.
@ eDPF_AtomicWrite
This flag is deprecated and ignored - all log writes are atomic.
@ eDPF_ErrCodeUseSeverity
Use severity from error code (default)
@ eDPF_Location
Include class and function if any.
@ eDPF_OmitSeparator
No '—' separator before message.
@ eDPF_MergeLines
Escape EOLs.
@ eDPF_ErrCodeMsgInFront
Put ErrCode text in front of the message.
@ eDPF_ErrCodeExplanation
Error explanation (default)
@ eDPF_IsNote
Print "Note[X]" severity name.
@ eDPF_DateTime
Include date and time.
@ eDPF_ErrorID
Error code and subcode (default)
@ eDPF_Severity
Severity (default)
@ eDPF_OmitInfoSev
No sev. indication if eDiag_Info.
@ eDPF_Default
Use global default flags (merge with).
@ eDPF_IsConsole
Send the message to 'console' regardless of it's severity.
@ eDPF_Trace
Default flags to use when tracing.
@ eDPF_File
File name (not full path)
@ eDPF_UseExactUserFlags
Use flags provided by user as-is, do not allow CNcbiDiag to replace "important" flags by the globally...
@ eDPF_ImportantFlagsMask
Important bits which should be taken from the globally set flags even if a user attempts to override ...
@ eDPF_ErrCodeMessage
Error code message (default)
@ eDPF_LongFilename
Full file path.
@ eDPF_AppLog
Post message to application log.
@ eDPF_Prefix
Prefix (default)
@ eDiagSC_Enable
Enable change severity level.
@ eDiagSC_Disable
Disable change severity level.
@ eDiagSC_Unknown
Status of changing severity is unknown (first call)
@ eDCM_Discard
Discard the collected messages without flushing.
@ eDCM_Init
Start collecting messages (with limit), do nothing if already initialized.
@ eDCM_NoChange
Continue collecting messages if already started.
@ eDCM_InitNoLimit
Start collecting messages without limit (must stop collecting later using eDCM_Flush or eDCM_Discard)...
@ eDCM_Flush
Flush the collected messages and stop collecting.
@ fNoPrefix
No std prefix.
@ eDS_Default
Try standard log file (app.name + ".log") in /log/, use stderr on failure.
@ eDS_ToMemory
Keep in a temp.memory buffer, see FlushMessages()
@ eDS_User
Leave as was previously set (or not set) by user.
@ eDS_Disable
Don't write it anywhere.
@ eDS_AppSpecific
Call the application's SetupDiag_AppSpecific()
@ eDS_ToStdlog
Try standard log file (app.name + ".log") in /log/ and current directory, use stderr if both fail.
@ eDS_ToStdout
To standard output stream.
@ eDS_ToStderr
To standard error stream.
@ eDS_ToSyslog
To system log daemon.
@ ePostNumber_NoIncrement
Get post number without incrementing it.
@ ePostNumber_Increment
Increment and return the new post number.
@ eEvent_RequestStop
Finish processing request.
@ eEvent_PerfLog
Performance log.
@ eEvent_RequestStart
Start processing request.
@ eEvent_Start
Application start.
@ eEvent_Extra
Other application events.
@ eEvent_Stop
Application exit.
@ eDT_Enable
Enable messages of severity "eDiag_Trace".
@ eDT_Disable
Ignore messages of severity "eDiag_Trace".
@ eDT_Default
Restores the default tracing context.
@ ePrintCapped
Print collected messages at reduced severity.
@ ePrint
Print all collected messages as is.
@ eDiscard
Discard collected messages, default.
@ eLogRate_Trace
Trace log.
@ eLogRate_App
Application log.
@ fOnFork_ResetTimer
Reset execution timer.
@ fOnFork_AsyncSafe
After a fork() in a multithreaded program, the child can safely call only async-signal-safe functions...
@ fOnFork_PrintStart
Log app-start.
@ eHitID_Request
Check if per-request hit id is set.
@ eHidID_Existing
Check if any hit is already available (will not be generated on request).
@ eDiagFile_Trace
Trace log file.
@ eDiagFile_Perf
Perf log file.
@ eDiagFile_Err
Error log file.
@ eDiagFile_All
All log files.
@ eDiagFile_Log
Access log file.
@ eDiagAppState_RequestEnd
RE.
@ eDiagAppState_AppEnd
AE.
@ eDiagAppState_AppBegin
AB.
@ eDiagAppState_RequestBegin
RB.
@ eDiagAppState_NotSet
Reserved value, never used in messages.
@ eDiagAppState_Request
R.
@ eDiag_Trace
Trace message.
@ eDiag_Info
Informational message.
@ eDiag_Error
Error message.
@ eDiag_Warning
Warning message.
@ eDiag_Fatal
Fatal error – guarantees exit(or abort)
@ eDiagSevMin
Verbosity level for min. severity.
@ eDiag_Critical
Critical error message.
@ eDiagSevMax
Verbosity level for max. severity.
@ eProp_Default
Auto-mode for known properties, local for others.
@ eProp_Thread
The property has separate value in each thread.
@ eProp_Global
The property is global for the application.
@ eDiagFilter_All
for all non-FATAL
@ eDiagFilter_Post
for all non-TRACE, non-FATAL
@ eDiagFilter_Trace
for TRACEs only
const string & GetModule(void) const
Get module name used for reporting.
bool IsSetFlag(EFlags flag) const
Check if the flag is set.
virtual void ReportExtra(ostream &out) const
Report "non-standard" attributes.
virtual const char * GetType(void) const
Get class name as a string.
void Critical(CExceptionArgs_Base &args)
void Error(CExceptionArgs_Base &args)
const string & GetFile(void) const
Get file name used for reporting.
TErrCode GetErrCode(void) const
Get error code.
#define NCBI_THROW(exception_class, err_code, message)
Generic macro to throw an exception, given the exception class, error code and message string.
const string & GetMsg(void) const
Get message string.
void Warning(CExceptionArgs_Base &args)
bool HasMainText(void) const
Check if exception has main text in the chain.
const string & GetClass(void) const
Get class name used for reporting.
#define NCBI_THROW2(exception_class, err_code, message, extra)
Throw exception with extra parameter.
const string & GetFunction(void) const
Get function name used for reporting.
EDiagSev GetSeverity(void) const
Get exception severity.
virtual const char * GetErrCodeString(void) const
Get error code interpreted as text.
int GetLine(void) const
Get line number where error occurred.
const CException * GetPredecessor(void) const
Get "previous" exception from the backlog.
void Info(CExceptionArgs_Base &args)
const CStackTrace * GetStackTrace(void) const
Get the saved stack trace if available or NULL.
@ eCore
Generic corelib error.
@ fConsole
Mark the exception with this flag if the exception is supposed to be extra-visible,...
static string NormalizePath(const string &path, EFollowLinks follow_links=eIgnoreLinks)
Normalize a path.
static string CreateAbsolutePath(const string &path, ERelativeToWhat rtw=eRelativeToCwd)
Get an absolute path from some, possibly relative, path.
string GetDir(EIfEmptyPath mode=eIfEmptyPath_Current) const
Get the directory component for this directory entry.
static bool IsAbsolutePath(const string &path)
Check if a "path" is absolute for the current OS.
string GetBase(void) const
Get the base entry name without extension.
static mode_t MakeModeT(TMode user_mode, TMode group_mode, TMode other_mode, TSpecialModeBits special)
Construct mode_t value from permission modes.
static Uint8 GetFreeDiskSpace(const string &path)
Get free disk space information.
static string ConvertToOSPath(const string &path)
Convert "path" on any OS to the current OS-dependent path.
static char GetPathSeparator(void)
Get path separator symbol specific for the current platform.
static string ConcatPath(const string &first, const string &second)
Concatenate two parts of the path for the current OS.
string GetExt(void) const
Get extension name.
virtual bool Exists(void) const
Check existence of file.
@ fRF_Overwrite
Remove destination if it exists.
@ fWrite
Write permission.
TObjectType * GetPointer(void) THROWS_NONE
Get pointer,.
void AddReference(void) const
Add reference to object.
void RemoveReference(void) const
Remove reference to object.
static void EnableConfigDump(bool enable)
@ eParam_NoThread
Do not use per-thread values.
uint32_t Uint4
4-byte (32-bit) unsigned integer
uint16_t Uint2
2-byte (16-bit) unsigned integer
int64_t Int8
8-byte (64-bit) signed integer
uint64_t Uint8
8-byte (64-bit) unsigned integer
static TPid GetPid(void)
Get process identifier (pid) for the current process.
virtual const string & Get(const string §ion, const string &name, TFlags flags=0) const
Get the parameter value.
virtual void EnumerateEntries(const string §ion, list< string > *entries, TFlags flags=fAllLayers) const
Enumerate parameter names for a specified section.
virtual string GetString(const string §ion, const string &name, const string &default_value, TFlags flags=0) const
Get the parameter string value.
#define END_NCBI_SCOPE
End previously defined NCBI scope.
#define BEGIN_NCBI_SCOPE
Define ncbi namespace.
CNcbiIstream & NcbiGetlineEOL(CNcbiIstream &is, string &str, string::size_type *count=NULL)
Read from "is" to "str" the next line (taking into account platform specifics of End-of-Line)
bool IsOssEmpty(CNcbiOstrstream &oss)
IO_PREFIX::ostream CNcbiOstream
Portable alias for ostream.
CNcbistrstream_Base< IO_PREFIX::ostrstream, IOS_BASE::out > CNcbiOstrstream
IO_PREFIX::istream CNcbiIstream
Portable alias for istream.
IO_PREFIX::ifstream CNcbiIfstream
Portable alias for ifstream.
static bool StringToBool(const CTempString str)
Convert string to bool.
NCBI_NS_STD::string::size_type SIZE_TYPE
static string Int8ToString(Int8 value, TNumToStringFlags flags=0, int base=10)
Convert Int8 to string.
void Parse(const CTempString str, NStr::EMergeDelims merge_argsep=NStr::eMergeDelims)
Parse the string.
static string DoubleToString(double value, int precision=-1, TNumToStringFlags flags=0)
Convert double to string.
string Merge(void) const
Merge name-value pairs into a single string using the currently set separators and the provided encod...
static int StringToNonNegativeInt(const CTempString str, TStringToNumFlags flags=0)
Convert string to non-negative integer value.
static int CompareNocase(const CTempString s1, SIZE_TYPE pos, SIZE_TYPE n, const char *s2)
Case-insensitive compare of a substring with another string.
static int StringToInt(const CTempString str, TStringToNumFlags flags=0, int base=10)
Convert string to int.
static Int8 StringToInt8(const CTempString str, TStringToNumFlags flags=0, int base=10)
Convert string to Int8.
static list< string > & Split(const CTempString str, const CTempString delim, list< string > &arr, TSplitFlags flags=0, vector< SIZE_TYPE > *token_pos=NULL)
Split a string using specified delimiters.
static bool MatchesMask(CTempString str, CTempString mask, ECase use_case=eCase)
Match "str" against the "mask".
static string LongToString(long value, TNumToStringFlags flags=0, int base=10)
Convert Int to string.
const char * g_GetNcbiString(ENcbiStrings what)
CTempString & assign(const char *src_str, size_type len)
Assign new values to the content of the a string.
static const string BoolToString(bool value)
Convert bool to string.
static string JoinNumeric(TInputIterator from, TInputIterator to, const CTempString &delim)
static string IntToString(int value, TNumToStringFlags flags=0, int base=10)
Convert int to string.
static int HexChar(char ch)
Convert character to integer.
const char * data(void) const
Return a pointer to the array represented.
EStringType
Type of string to be decoded.
IStringDecoder * GetDecoder(void)
Get decoder or NULL. Does not affect decoder ownership.
EStringType
Type of string to be decoded.
virtual string Decode(const CTempString src, EStringType stype) const =0
Decode the string.
static string UIntToString(unsigned int value, TNumToStringFlags flags=0, int base=10)
Convert UInt to string.
static bool StartsWith(const CTempString str, const CTempString start, ECase use_case=eCase)
Check if a string starts with a specified prefix value.
const TStrPairs & GetPairs(void) const
Read data.
static Uint8 StringToUInt8(const CTempString str, TStringToNumFlags flags=0, int base=10)
Convert string to Uint8.
static bool SplitInTwo(const CTempString str, const CTempString delim, string &str1, string &str2, TSplitFlags flags=0)
Split a string into two pieces using the specified delimiters.
size_type length(void) const
Return the length of the represented array.
static string ULongToString(unsigned long value, TNumToStringFlags flags=0, int base=10)
Convert unsigned long to string.
static bool IsIPAddress(const CTempStringEx str)
Check if the string contains a valid IP address.
static bool EqualNocase(const CTempString s1, SIZE_TYPE pos, SIZE_TYPE n, const char *s2)
Case-insensitive equality of a substring with another string.
static enable_if< is_arithmetic< TNumeric >::value||is_convertible< TNumeric, Int8 >::value, string >::type NumericToString(TNumeric value, TNumToStringFlags flags=0, int base=10)
Convert numeric value to string.
static string & ReplaceInPlace(string &src, const string &search, const string &replace, SIZE_TYPE start_pos=0, SIZE_TYPE max_replace=0, SIZE_TYPE *num_replace=0)
Replace occurrences of a substring within a string.
static string & ToUpper(string &str)
Convert string to upper case – string& version.
static string TruncateSpaces(const string &str, ETrunc where=eTrunc_Both)
Truncate spaces in a string.
const char *const kEmptyCStr
Empty "C" string (points to a '\0').
size_type size(void) const
Return the length of the represented array.
static string & ToLower(string &str)
Convert string to lower case – string& version.
static string UInt8ToString(Uint8 value, TNumToStringFlags flags=0, int base=10)
Convert UInt8 to string.
@ fConvErr_NoThrow
Do not throw an exception on error.
@ fSplit_Tokenize
All delimiters are merged and trimmed, to get non-empty tokens only.
@ fSplit_MergeDelimiters
Merge adjacent delimiters.
@ fDoubleFixed
DoubleToString*(): Use n.nnnn format for double conversions.
@ eNocase
Case insensitive compare.
#define NCBI_HAVE_CONDITIONAL_VARIABLE
CConditionVariable –.
bool Run(TRunMode flags=fRunDefault)
Run the thread.
void Wait(void)
Wait on semaphore.
static void SetCurrentThreadName(const CTempString &)
Set name for the current thread.
void SetValue(TValue *value, FCleanup cleanup=0, void *cleanup_data=0, CTlsBase::ENativeThreadCleanup native=CTlsBase::eSkipCleanup)
void Post(unsigned int count=1)
Increment the semaphore by "count".
void Join(void **exit_data=0)
Wait for the thread termination.
static TThreadSystemID GetCurrentThreadSystemID(void)
Get the current thread ID.
bool IsRunning(void) const
Check state of stopwatch.
double Restart(void)
Return time elapsed since first Start() or last Restart() call (in seconds).
double Elapsed(void) const
Return time elapsed since first Start() or last Restart() call (in seconds).
CTime Truncate(const CTime &t)
string AsString(const CTimeFormat &format=kEmptyStr, TSeconds out_tz=eCurrentTimeZone) const
Transform time to string.
bool IsEmpty(void) const
Is time object empty (date and time)?
string AsString(const CTimeFormat &fmt=kEmptyStr) const
Transform stopwatch time to string.
CTime GetFastLocalTime(void)
Quick and dirty getter of local time.
CTime GetLocalTime(void)
Get local time.
@ eCurrent
Use current time. See also CCurrentTime.
@ eGmt
GMT (Greenwich Mean Time)
static const unsigned int kNoLimit
Special value for maximum number of allowed requests per period.
@ eErrCode
Return immediately with err code == FALSE.
@ eDiscrete
Uses fixed time frame to check number of requests.
string GetExtraValue(EExtra key, const string &default_value=kEmptyStr) const
int GetMajor(void) const
Major version.
const SBuildInfo & GetBuildInfo() const
Get build info (date and tag, if set)
const CVersionInfo & GetVersionInfo() const
Get version information.
static CVersionInfo GetPackageVersion(void)
int GetMinor(void) const
Minor version.
static string GetPackageName(void)
int GetPatchLevel(void) const
Patch level.
#define NCBI_SBUILDINFO_DEFAULT()
static string ExtraNameAppLog(EExtra key)
@ eRevision
Not necessarily numeric.
@ eSubversionRevision
Numeric if present.
@ eStableComponentsVersion
#define ErrCode()
Get the error code for the last failed system function.
unsigned int
A callback function used to compare two keys in a database.
#define NCBI_DEVELOPMENT_VER
Definition of all error codes used in corelib (xncbi.lib).
where boath are integers</td > n< td ></td > n</tr > n< tr > n< td > tse</td > n< td > optional</td > n< td > String</td > n< td class=\"description\"> TSE option controls what blob is orig
if(yy_accept[yy_current_state])
CBioseq_Base_Info & GetBase(CTSE_Info &tse, const CBioObjectId &id)
static void text(MDB_val *v)
const struct ncbi::grid::netcache::search::fields::KEY key
const GenericPointer< typename T::ValueType > T2 value
const CharType(& source)[N]
int strcmp(const char *str1, const char *str2)
#define NCBI_TEAMCITY_BUILDCONF_NAME
#define NCBI_TEAMCITY_BUILD_ID
#define NCBI_SUBVERSION_REVISION
#define NCBI_TEAMCITY_BUILD_NUMBER
#define NCBI_TEAMCITY_PROJECT_NAME
Defines process management classes.
Common macro to detect used sanitizers and suppress memory leaks if run under LeakSanitizer.
#define NCBI_LSAN_DISABLE_GUARD
String constants used in NCBI C/C++ toolkit.
bool IsSuppressedDebugSystemMessageBox()
Check if system message box has been suppressed for debug library.
void SuppressSystemMessageBox(TSuppressSystemMessageBox mode=fSuppress_Default)
Suppress popup messages on execution errors.
static const char * kLogName_Stream
bool x_IsEncodableChar(char c)
CDiagContext::TUID s_CreateUID(CDiagContext::TUID base)
static CSafeStatic< NCBI_PARAM_TYPE(Log, Session_Id)> s_DefaultSessionId
static const int kDiagW_Host
const int kLogReopenDelay
static CSafeStatic< SNcbiApplogKeywordsInit::TKeywords, SNcbiApplogKeywordsInit > s_NcbiApplogKeywords
static const char * kUnknown_App
static const int kDiagW_RID
static CSafeStatic< CDiagFilter > s_TraceFilter
NCBI_PARAM_DEF_EX(bool, Diag, Old_Post_Format, true, eParam_NoThread, DIAG_OLD_POST_FORMAT)
const char * find_match(char lsep, char rsep, const char *start, const char *stop)
Uint8 s_GetThreadId(void)
bool OpenLogFileFromConfig(const string &logname)
static TDiagPostFlags s_PostFlags
void * s_DiagHandlerInitializer
static bool s_CreateHandler(const string &fname, unique_ptr< CStreamDiagHandler_Base > &handler, EDiagFileType file_type)
NCBI_PARAM_ENUM_DEF_EX(EDiagSev, Diag, Tee_Min_Severity, kTeeMinSeverityDef, eParam_NoThread, DIAG_TEE_MIN_SEVERITY)
static CSafeStatic< CDiagRecycler > s_DiagRecycler
static CSafeStatic< NCBI_PARAM_TYPE(Diag, AppLog_Rate_Period)> s_AppLogRatePeriod
bool s_IsSpecialLogName(const string &name)
static CSafeStatic< NCBI_PARAM_TYPE(Log, Http_Hit_Id)> s_HttpHitId
static string s_GetExceptionText(const CException *pex)
static CSafeStatic< NCBI_PARAM_TYPE(Diag, Old_Post_Format)> s_OldPostFormat(CSafeStaticLifeSpan(CSafeStaticLifeSpan::eLifeSpan_Long, 2))
static const char * s_LegacyAppStateStr[]
static void s_UnsetDiagPostFlag(TDiagPostFlags &flags, EDiagPostFlag flag)
string s_ReadString(const char *filename)
void EndmFatal(const CNcbiDiag &diag)
void s_FormatStackTrace(CNcbiOstream &os, const CStackTrace &trace)
static FAbortHandler s_UserAbortHandler
Uint8 s_ParseInt(const string &message, size_t &pos, size_t width, char sep)
static bool s_DiagPostFlagsInitialized
static CSafeStatic< NCBI_PARAM_TYPE(Diag, ErrLog_Rate_Limit)> s_ErrLogRateLimit
static const char * kLogName_None
static const int kDiagW_Client
static bool s_SplitLogFile
DEFINE_STATIC_MUTEX(s_DiagMutex)
CDiagBuffer & GetDiagBuffer(void)
const CDiagContext::TUID kUID_Mult
bool IsGlobalProperty(const string &name)
static const char * kUnknown_Session
static const Uint8 kOwnerTID_None
static CTime s_GetFastTime(void)
static const int kDiagW_Session
static const char * s_AppStateStr[]
static const char * kUnknown_Client
static const char * kLogName_Tee
CTempString s_ParseStr(const string &message, size_t &pos, char sep, bool optional=false)
static const int kDiagW_SN
EDiagAppState s_StrToAppState(const string &state)
static CSafeStatic< NCBI_PARAM_TYPE(Diag, Print_System_TID)> s_PrintSystemTID
static CDiagHandler * s_CreateDefaultDiagHandler(void)
EDiagSev AdjustApplogPrintableSeverity(EDiagSev sev)
CNcbiIstream & operator>>(CNcbiIstream &in, CLogRateLimit &lim)
static CSafeStatic< NCBI_PARAM_TYPE(Diag, Max_Line_Length)> s_MaxLineLength
static const int kDiagW_TID
const CDiagContext::TUID kUID_InitBase
static string s_GetLogConfigString(const CTempString name, const CTempString defval, CNcbiRegistry *config)
@ eDiagMergeLines_Default
static const char * kNcbiApplogKeywordStrings[]
static const char * kLogName_Stdout
static const char * kDiagTimeFormat
NCBI_PARAM_STATIC_PROXY(CLogRateLimit, CLogRateLimit::TValue)
typedef NCBI_PARAM_TYPE(Diag, Tee_To_Stderr) TTeeToStderr
static const TDiagPostFlags s_DefaultPostFlags
static bool s_FinishedSetupDiag
static const int kDiagW_AppState
static CSafeStatic< CAtomicCounter_WithAutoInit > s_ReopenEntered
const TDiagPostFlags kApplogDiagPostFlags
static CSafeStatic< NCBI_PARAM_TYPE(Diag, TraceLog_Rate_Limit)> s_TraceLogRateLimit
const char * s_AppStateToStr(EDiagAppState state)
static const char * kUnknown_Host
static bool s_GetLogConfigBool(const CTempString name, bool defval, CNcbiRegistry *config)
static CSafeStatic< NCBI_PARAM_TYPE(Diag, TraceLog_Rate_Period)> s_TraceLogRatePeriod
CDiagContext_Extra g_PostPerf(int status, double timespan, SDiagMessage::TExtraArgs &args)
static const int kDiagW_UID
static void s_SetDiagPostFlag(TDiagPostFlags &flags, EDiagPostFlag flag)
static TDiagPostFlags s_SetDiagPostAllFlags(TDiagPostFlags &flags, TDiagPostFlags new_flags)
NCBI_PARAM_ENUM_ARRAY(EDiagSev, Diag, Tee_Min_Severity)
const char * str_rev_str(const char *begin_str, const char *end_str, const char *str_search)
static CSafeStatic< NCBI_PARAM_TYPE(Log, Http_Session_Id)> s_HttpSessionId
static CSafeStatic< NCBI_PARAM_TYPE(Diag, Log_Size_Limit)> s_LogSizeLimit
NCBI_PARAM_DECL(bool, Diag, Old_Post_Format)
void * InitDiagHandler(void)
static const char * kRootLog
CDiagHandler * s_DefaultHandler
static thread_local CDiagContextThreadData * s_ThreadDataCache
static CSafeStatic< CDiagFilter > s_PostFilter
static CSafeStatic< NCBI_PARAM_TYPE(Diag, Disable_AppLog_Messages)> s_DisableAppLog
static CSafeStatic< NCBI_PARAM_TYPE(Diag, ErrLog_Rate_Period)> s_ErrLogRatePeriod
static CSafeStatic< unique_ptr< string > > s_HostLocation
static const char * kLogName_Memory
static CSafeStatic< unique_ptr< string > > s_HostRole
static const char * kLogName_Unknown
static thread_local EThreadDataState s_ThreadDataState(eUninitialized)
string GetDefaultLogLocation(CNcbiApplication &app)
static const char s_ExtraEncodeChars[256][4]
static CSafeStatic< NCBI_PARAM_TYPE(Diag, AutoWrite_Context)> s_AutoWrite_Context
static bool s_DiagUseRWLock
static const int kDiagW_PID
static CSafeStatic< NCBI_PARAM_TYPE(Log, Hit_Id)> s_HitId
static const char * kExtraTypeArgName
static CSafeStatic< NCBI_PARAM_TYPE(Log, Client_Ip)> s_DefaultClientIp
const EDiagSev kTeeMinSeverityDef
bool s_ParseErrCodeInfoStr(string &str, const SIZE_TYPE line, int &x_code, int &x_severity, string &x_message, bool &x_ready)
static CSafeStatic< NCBI_PARAM_TYPE(Diag, AppLog_Rate_Limit)> s_AppLogRateLimit
static CSafeStatic< CRWLock > s_DiagRWLock(CSafeStaticLifeSpan(CSafeStaticLifeSpan::eLifeSpan_Long, 1))
NCBI_PARAM_ENUM_DECL(EDiagSev, Diag, Tee_Min_Severity)
static const char * kLogName_Stderr
Defines NCBI C++ service classes and functions for diagnostic APIs, classes, and macros.
Defines NCBI C++ exception handling.
Defines classes: CDirEntry, CFile, CDir, CSymLink, CMemoryFile, CFileUtil, CFileLock,...
std::istream & in(std::istream &in_, double &x_)
double f(double x_, const double &y_)
static const char * suffix[]
static const char * prefix[]
Defines CRequestContext class for NCBI C++ diagnostic API.
static CNamedPipeClient * client
This class allows to add build info (date and tag) to application version.
SDiagErrCodeDescription –.
bool Append(const string &str)
unordered_set< string > TKeywords
void Cleanup(TKeywords &)
static atomic< thread::id > sm_ThreadID
static SDiagMessage Report(EDiagSev &sev)
static atomic< bool > sm_Reported
Portable system-logging API.
CRef< CTestThread > thr[k_NumThreadsMax]
static wxAcceleratorEntry entries[3]