** environ;
74 #define NCBI_USE_ERRCODE_X Corelib_Diag 95 booldiag_unlocked = s_DiagMutex.TryLock();
101 "Cannot switch diagnostic to RW-lock - mutex is locked.");
103s_DiagMutex.Unlock();
110 if(!diag_unlocked) {
113 "Cannot switch diagnostic to mutex - RW-lock is locked.");
147s_DiagPostMutex.Lock();
161s_DiagPostMutex.Unlock();
164s_DiagMutex.Unlock();
235 #if defined(NCBI_POSIX_THREADS) && defined(HAVE_PTHREAD_ATFORK) 238 static voids_NcbiDiagPreFork(
void)
242 static voids_NcbiDiagPostFork(
void)
244s_DiagMutex.Unlock();
257DIAG_OLD_POST_FORMAT);
264DIAG_AUTOWRITE_CONTEXT);
270DIAG_PRINT_SYSTEM_TID);
278DIAG_ASSERT_ON_ABORT);
283DIAG_LOG_SIZE_LIMIT);
289DIAG_MAX_LINE_LENGTH);
324lim.
Set(NStr::StringToNumeric<CLogRateLimit::TValue>(s));
344DIAG_APPLOG_RATE_PERIOD);
356DIAG_ERRLOG_RATE_PERIOD);
368DIAG_TRACELOG_RATE_PERIOD);
419DIAG_LOG_ENVIRONMENT);
432DIAG_DISABLE_APPLOG_MESSAGES);
456 returns_DisabledAppLogEvents->
Get();
464 switch(disabled_events) {
571 x_Init(print_severity, collect_severity, action);
588psev = CDiagBuffer::sm_PostSeverity;
592? psev : print_severity;
594? csev : collect_severity;
652 str_rev_str(
const char* begin_str,
const char* end_str,
const char* str_search)
654 if(begin_str ==
NULL)
656 if(end_str ==
NULL)
658 if(str_search ==
NULL)
661 const char* search_char = str_search + strlen(str_search);
662 const char* cur_char = end_str;
668}
while(*cur_char != *search_char && cur_char != begin_str);
669 if(*cur_char != *search_char)
672 while(search_char != str_search);
694 const char* curr_funct,
699m_CurrFunctName(curr_funct),
717 const string& curr_funct,
718 const string& module)
722m_CurrFunctName(
""),
737 const char* cur_extension = strrchr(
m_File,
'.');
738 if(cur_extension ==
NULL)
741 if(*(cur_extension + 1) !=
'\0') {
747 return strcmp(cur_extension,
"cpp") == 0 ||
748 strcmp(cur_extension,
"C") == 0 ||
749 strcmp(cur_extension,
"c") == 0 ||
750 strcmp(cur_extension,
"cxx") == 0;
808 if(*(stop - 1) != rsep)
returnstop;
810 const char* pos = stop - 2;
811 for(; pos > start; pos--) {
815 else if(*pos == lsep) {
816 if(--balance == 0)
break;
819 return(pos <= start) ?
NULL: pos;
834 const char* end_str =
find_match(
'(',
')',
849 const char* start_str =
NULL;
852 const char* start_str_tmp =
854 boolhas_class = start_str_tmp !=
NULL;
855 if(start_str_tmp !=
NULL) {
856start_str = start_str_tmp + 2;
859 if(start_str_tmp !=
NULL) {
860start_str = start_str_tmp + 1;
864 const char* cur_funct_name =
866 while(cur_funct_name && *cur_funct_name &&
867(*cur_funct_name ==
'*'|| *cur_funct_name ==
'&')) {
870 size_tcur_funct_name_len = end_str - cur_funct_name;
877 const char* cur_class_name =
879 while(cur_class_name && *cur_class_name &&
880(*cur_class_name ==
'*'|| *cur_class_name ==
'&')) {
883 size_tcur_class_name_len = end_str - cur_class_name;
897 #if defined(NCBI_POSIX_THREADS) && defined(HAVE_PTHREAD_ATFORK) 898pthread_atfork(s_NcbiDiagPreFork,
935 enumEThreadDataState {
943 const automain_thread_id = std::this_thread::get_id();
945 template<
typename_T,
typename_MainCleanup =
void,
typename_ThreadCleanup = _MainCleanup>
956 template<
typename...TArgs,
typename= std::enable_if_t<std::is_constructible_v<
_T, TArgs...>>>
959 void* ptr =
static_cast<void*
>(m_memory.data());
964 auto data=
new(ptr)
_T(std::forward<TArgs>(args)...);
965 if(std::this_thread::get_id() == main_thread_id) {
969 autocleaner =
newTMainThreadCleaner(span,
data);
978 if(std::this_thread::get_id() == main_thread_id) {
981 ifconstexpr (!std::is_void_v<_ThreadCleanup>) {
982_ThreadCleanup{}(ptr);
990 operator _T*() {
return reinterpret_cast<_T*
>(m_memory.data()); }
991 operator _T&() {
return**
this; }
1000m_InstanceMutex =
nullptr;
1005TInstanceMutexGuard&
)
1008TMainThreadCleaner* cleaner = (TMainThreadCleaner*)safe_static;
1009 _T* ptr =
static_cast<_T*
>(
const_cast<void*
>(cleaner->x_ReleasePtr()));
1010 ifconstexpr (!std::is_void_v<_MainCleanup>) {
1011_MainCleanup{}(ptr);
1024std::array<
uint8_t,
sizeof(
_T)> m_memory;
1027 structCDiagContextThreadData_Cleanup
1045thread_local EThreadDataState s_ThreadDataState(eUninitialized);
1058: m_DiagBuffer(new CDiagBuffer),
1060m_ThreadPostNumber(0),
1061m_DiagCollectionSize(0)
1066s_ThreadDataState = eInitialized;
1072 if( s_ThreadDataCache ==
this) {
1073s_ThreadDataCache = 0;
1074s_ThreadDataState = eDeinitialized;
1099 if(s_ThreadDataState != eInitialized) {
1102EThreadDataState thread_data_state = s_ThreadDataState;
1103 switch(thread_data_state) {
1107 caseeUninitialized:
1108s_ThreadDataState = eInitializing;
1112cerr <<
"FATAL ERROR: inappropriate recursion initializing NCBI" 1113 " diagnostic framework.\n";
1117 caseeDeinitialized:
1118s_ThreadDataState = eReinitializing;
1119cerr <<
"Reinitializing NCBI diagnostic framework\n";
1122 caseeReinitializing:
1123cerr <<
"FATAL ERROR: NCBI diagnostic framework no longer" 1131s_ThreadDataCache = g_thread_data;
1132 return*s_ThreadDataCache;
1170 "Using the same CRequestContext in multiple threads is unsafe!" 1198TCollectGuards::iterator itg = find(
1205unique_ptr<CDiagLock> lock;
1211 if(itc->m_ThrPost >= start
1213itc->m_Severity = cap;
1224 if(lock.get() ==
nullptr) {
1233 handler->PostToConsole(*itc);
1240 if(itc->m_Severity ==
eDiag_Trace&& !allow_trace) {
1243 if(itc->m_Severity < post_sev) {
1249 if(discarded > 0) {
1251 " messages due to collection limit. Set " 1252 "DIAG_COLLECT_LIMIT to increase the limit.");
1315 "NS",
"PB",
"P",
"PE",
"RB",
"R",
"RE" 1405m_AppNameSet(
false),
1406m_LoggedHitId(
false),
1408m_ExitCodeSet(
false),
1414GetLogRate_Limit(eLogRate_App),
1415 CTimeSpan((long)GetLogRate_Period(eLogRate_App)),
1420GetLogRate_Limit(eLogRate_Err),
1421 CTimeSpan((long)GetLogRate_Period(eLogRate_Err)),
1426GetLogRate_Limit(eLogRate_Trace),
1427 CTimeSpan((long)GetLogRate_Period(eLogRate_Trace)),
1431m_AppLogSuspended(
false),
1432m_ErrLogSuspended(
false),
1433m_TraceLogSuspended(
false)
1579 bool* show_warning)
1581 boolapproved =
true;
1595 switch(
msg.m_Severity ) {
1641 if(
sm_PID== new_pid) {
1650 Print(
"action",
"fork").
1651 Print(
"parent_guid",
ctx.GetStringUID(old_uid)).
1660 if(
sm_PID== new_pid) {
1720 return(TUID(base) << 48) |
1721((TUID(pid) & 0xFFFF) << 32) |
1722((TUID(
t) & 0xFFFFFFF) << 4) |
1729 const string& host =
GetHost();
1730 for(
autoc : host) {
1743 #if defined(NCBI_OS_UNIX) 1745 structutsname
buf;
1746 if(uname(&
buf) >= 0) {
1747 const char* s =
buf.nodename;
1781 inthi =
int((uid >> 32) & 0xFFFFFFFF);
1782 intlo =
int(uid & 0xFFFFFFFF);
1783snprintf(
buf, buflen,
"%08X%08X", hi, lo);
1811uid &= ~((
TUID)0xFFFFFFF << 4);
1813 returnuid | ((
TUID(
t) & 0xFFFFFFF) << 4);
1832 Uint8tid = (thr_data.
GetTID() & 0xFFFFFF) << 40;
1834 if( !is_default ) {
1838rid = ((
Uint8)0xFFFFFF) << 16;
1845snprintf(
buf, 33,
"%08X%08X%08X%08X", b3, b2, b1, b0);
1871 if( !
m_Host->IsEmpty() ) {
1872 return m_Host->GetOriginalString();
1880 if(ncbi_host && *ncbi_host) {
1882 return m_Host->GetOriginalString();
1885 #if defined(NCBI_OS_UNIX) 1888 structutsname
buf;
1889 if(uname(&
buf) >= 0) {
1891 return m_Host->GetOriginalString();
1896 #if defined(NCBI_OS_MSWIN) 1899 if( compname && *compname ) {
1901 return m_Host->GetOriginalString();
1907 if( servaddr && *servaddr ) {
1910 return m_Host->GetOriginalString();
1916 if( !
m_Host->IsEmpty() ) {
1917 return m_Host->GetEncodedString();
1924 return m_Host->GetEncodedString();
1930 return m_Host->GetOriginalString();
1936 return m_Host->GetEncodedString();
1942 m_Host->SetString(hostname);
1990 ERR_POST(
"Application name cannot be changed.");
1997 ERR_POST(
"Illegal characters in application name: '"<< app_name <<
1998 "', using URL-encode.");
2034 const string&
value,
2081 if( !
value.empty() ) {
2192gprop->first +
"="+ gprop->second);
2204 static const char* kCloudIdFile =
"/etc/ncbi/cloudid";
2205 CFilecloudid(kCloudIdFile);
2206 if( cloudid.
Exists() ) {
2209 while(!
in.eof() &&
in.good()) {
2212 size_tsep = s.find(
'\t');
2213 if(sep ==
NPOS)
continue;
2215 string value= s.substr(sep + 1);
2225 for(
char**
env= environ; *
env; ++
env) {
2234 f.LogFields(env_map);
2251 ctx.x_LogHitID(
true);
2271: m_EventType(event_type),
2273m_Counter(new
int(1)),
2278m_AllowBadNames(
false)
2288m_Counter(new
int(1)),
2290m_PerfStatus(status),
2291m_PerfTime(timespan),
2293m_AllowBadNames(
false)
2295 if(args.empty())
return;
2305m_Typed(args.m_Typed),
2306m_PerfStatus(args.m_PerfStatus),
2307m_PerfTime(args.m_PerfTime),
2308m_Flushed(args.m_Flushed),
2309m_AllowBadNames(args.m_AllowBadNames)
2330 if( !role.empty() ) {
2331 Print(
"ncbi_role", role);
2333 if( !loc.empty() ) {
2334 Print(
"ncbi_location", loc);
2354 Print(
"ncbi_app_package_version", pkv);
2358initializer_list<SBuildInfo::EExtra> bi_num = {
2367 if(!
value.empty()) {
2373 #if defined(NCBI_TEAMCITY_PROJECT_NAME) 2376 #if defined(NCBI_TEAMCITY_BUILDCONF_NAME) 2379 #if defined(NCBI_TEAMCITY_BUILD_NUMBER) 2382 #if defined(NCBI_TEAMCITY_BUILD_ID) 2400 Print(
"ncbi_app_version",
str);
2407initializer_list<SBuildInfo::EExtra> bi_num =
2413 if(!
value.empty()) {
2419 #if defined(NCBI_PRODUCTION_VER) 2420 Print(
"ncbi_app_prod_version", NStr::NumericToString<Uint8>(NCBI_PRODUCTION_VER));
2421 #elif defined(NCBI_DEVELOPMENT_VER) 2424 #if defined(NCBI_SC_VERSION) 2425 Print(
"ncbi_app_sc_version", NStr::NumericToString<Uint8>(NCBI_SC_VERSION));
2427 #if defined(NCBI_SUBVERSION_REVISION) 2458 boolapp_state_updated =
false;
2463app_state_updated =
true;
2470app_state_updated =
true;
2499 if( app_state_updated ) {
2523 if(
this!= &args) {
2551 "Attempt to set request start/stop arguments after flushing");
2585 "exec_time_msec_bit",
2597 "geo_latitude_hundredths",
2598 "geo_longitude_hundredths",
2599 "session_pageviews",
2601 "session_duration",
2604 "time_to_last_ping",
2611 "self_url_file_ext",
2612 "self_url_top_level_dir",
2613 "self_url_directory",
2625 "has_duplicate_nexus",
2626 "has_duplicate_phid",
2630 "has_multiple_phid",
2637 "multiple_session_hit",
2638 "multiple_session_ip",
2639 "ncbi_phid_first_render",
2640 "phid_from_other_request",
2641 "phid_stack_ambiguous_relationship",
2642 "phid_stack_has_fake_child",
2643 "phid_stack_has_fake_parent",
2644 "phid_stack_missing_child",
2645 "phid_stack_missing_parent",
2646 "phid_stack_multivalued",
2648 "session_bot_by_ip",
2649 "session_bot_by_rate",
2650 "session_bot_by_user_agent",
2652 "session_has_ping",
2655 "browser_major_version",
2656 "browser_platform",
2664 "applog_db_size_hit_fraction",
2665 "applog_db_machine",
2666 "applog_db_vol_id",
2668 "applog_db_date_tag",
2669 "applog_db_date_range",
2670 "applog_db_stream",
2671 "applog_db_create_time",
2672 "applog_db_modify_time",
2675 "applog_db_agent_host",
2676 "applog_db_agent_pid",
2677 "applog_db_agent_tid",
2678 "applog_db_volume_served_time",
2679 "phid_stack_missing_parent",
2680 "phid_stack_missing_child",
2681 "phid_stack_has_fake_child",
2682 "phid_stack_has_fake_parent",
2683 "phid_stack_ambiguous_relationship",
2684 "phid_stack_multivalued",
2685 "ncbi_phid_first_render",
2686 "multiple_session_hit",
2688 "session_has_ping",
2689 "has_duplicate_nexus",
2691 "has_multiple_phid",
2693 "session_bot_by_rate",
2694 "session_bot_by_user_agent",
2696 "session_bot_by_ip",
2698 "multiple_session_ip",
2711 for(
int i= 0;
i< sz; ++
i) {
2740 if(kw.find(name) == kw.end()) {
2741 m_Args->rbegin()->first.assign(name);
2744 stringrenamed =
"auto_renamed_applog_keyword__"+ name;
2745 m_Args->rbegin()->first.assign(renamed);
2747<<
"' is a reserved NCBI AppLog keyword, so it has been renamed to " 2784 #if !NCBI_INT8_IS_LONG 2795 #elif SIZEOF_LONG_LONG 2867 boolapp_state_updated =
false;
2871app_state_updated =
true;
2874 if( app_state_updated ) {
2883 boolapp_state_updated =
false;
2886app_state_updated =
true;
2889 if( app_state_updated ) {
2965NCBI_LOG_SESSION_ID);
2985 if( sid.empty() ) {
3030NCBI_LOG_CLIENT_IP);
3115 if( !phid.empty() ) {
3116 const char* c_env_job_id = getenv(
"JOB_ID");
3117 stringenv_job_id = c_env_job_id ?
string(c_env_job_id):
"";
3118 const char* c_env_task_id = getenv(
"SGE_TASK_ID");
3119 stringenv_task_id = c_env_task_id ?
string(c_env_task_id) :
"";
3120 if(env_task_id.find_first_not_of(
"0123456789") !=
NPOS) {
3125 if(!env_job_id.empty() && !env_task_id.empty()) {
3132 stringjid =
".000"+ env_job_id;
3133 stringtid =
".00"+ env_task_id;
3134 size_tjid_pos = phid.find(jid);
3135 if(jid_pos ==
NPOS) {
3141 if(phid.find(tid, jid_pos + jid.size()) ==
NPOS) {
3198unique_ptr<string> role(
new string);
3200 if(env_role && *env_role) {
3218unique_ptr<string> loc(
new string);
3220 if(env_loc && *env_loc) {
3270 const string& host =
msg.GetHost();
3272 stringsession =
msg.GetSession();
3273 const string& app =
msg.GetAppName();
3277ostr << setfill(
'0') << setw(
kDiagW_PID) <<
msg.m_PID <<
'/' 3281<< setfill(
' ') << setw(
kDiagW_AppState) << setiosflags(IOS_BASE::left)
3282<< app_state << resetiosflags(IOS_BASE::left)
3283<<
' '<< setw(0) << setfill(
' ') << uid <<
' ' 3284<< setfill(
'0') << setw(
kDiagW_SN) <<
msg.m_ProcPost <<
'/' 3287<< setfill(
' ') << setiosflags(IOS_BASE::left)
3294<< resetiosflags(IOS_BASE::left) << setw(0)
3303 if(
ctx.IsRunning() ) {
3306 ERR_POST_ONCE(
"Duplicate request-start or missing request-stop");
3307 ERR_POST(
Warning<<
"Duplicate request-start or missing request-stop");
3311 if( !
ctx.IsSetExplicitClientIP() ) {
3313 if( !
ip.empty() ) {
3314 ctx.SetClientIP(
ip);
3318 ctx.StartRequest();
3327 stringlog_args = s_LogEnvironment->
Get();
3328 if( !log_args.empty() ) {
3329list<string> log_args_list;
3333extra.
Print(
"LogEnvironment",
"true");
3341 ITERATE(list<string>, it, log_args_list) {
3342 const string&
val=
env.Get(*it);
3350log_args = s_LogRegistry->
Get();
3351 if( !log_args.empty() ) {
3352list<string> log_args_list;
3356extra.
Print(
"LogRegistry",
"true");
3363 ITERATE(list<string>, it, log_args_list) {
3364 stringsection, name;
3366 const string&
val= reg.
Get(section, name);
3377 const string& message)
3384 boolneed_space =
false;
3405 if( !
ctx.IsRunning() ) {
3408 ERR_POST_ONCE(
"Duplicate request-stop or missing request-start");
3409 ERR_POST(
Warning<<
"Duplicate request-stop or missing request-start");
3411 str.append(to_string(
ctx.GetRequestStatus())).append(1,
' ')
3412.append(
ctx.GetRequestTimer().AsString()).append(1,
' ')
3413.append(to_string(
ctx.GetBytesRd())).append(1,
' ')
3414.append(to_string(
ctx.GetBytesWr()));
3421 if( !message.empty() ) {
3423 str.append(1,
' ');
3425 str.append(message);
3430 str.data(),
str.size(),
3438CDiagBuffer::DiagHandler(mess);
3502it->m_NoTee =
true;
3535 size_tmin_pos = exe_path.length();
3539 if(!it->empty() && (*it)[0] !=
'/') {
3541 string mask=
"/"+ *it;
3542 if(
mask[
mask.length() - 1] !=
'/') {
3545 size_tpos = exe_path.find(
mask);
3546 if(pos < min_pos) {
3553 if(exe_path.substr(0, it->length()) == *it) {
3559 if( !web_dir.empty() ) {
3573 returnTLogTruncateParam::GetDefault();
3579TLogTruncateParam::SetDefault(
value);
3585 if( !logname.empty() ) {
3616 return config->GetString(
"LOG", name, defval);
3618 stringenvname =
"NCBI_CONFIG__LOG__";
3631 return config->GetBool(
"LOG", name, defval);
3633 stringenvname =
"NCBI_CONFIG__LOG__";
3650 const char* cmd_logfile)
3662CDiagBuffer::GetSeverityChangeEnabledFirstTime();
3668 ctx.InitMessages();
3671 ctx.InitMessages(
size_t(-1));
3696 boollog_set =
false;
3697 boolto_applog =
false;
3698 stringold_log_name;
3699 stringnew_log_name;
3702 if( old_handler ) {
3707 if( config_logfile.empty() ) {
3717 if(cmdline_first && cmd_logfile) {
3720new_log_name = cmd_logfile;
3725 if(!log_set && !applog_first && !config_logfile.empty()) {
3728new_log_name = config_logfile;
3732 if(!log_set && !cmdline_first && cmd_logfile &&
3736new_log_name = cmd_logfile;
3761 ctx.InitMessages(
size_t(-1));
3801 #if defined(NCBI_OS_UNIX) 3813 if( !log_base.empty() ) {
3814log_base =
CFile(log_base).
GetBase() + euid +
".log";
3817 if( !def_log_dir.empty() ) {
3821new_log_name = log_name;
3830new_log_name = log_name;
3838new_log_name = config_logfile;
3845new_log_name = log_name;
3855new_log_name = log_name;
3859 _TRACE_X(3,
"Failed to set log file to "+
3863 if(!log_set && !cmdline_first && cmd_logfile) {
3866new_log_name = cmd_logfile;
3872 if(!log_set && log_base.empty()) {
3874 if(
SetLogFile(default_fallback + euid) ) {
3876new_log_name = default_fallback;
3880 _TRACE_X(4,
"Failed to set log file to "<<
3883 const char* log_name = TTeeToStderr::GetDefault() ?
3885 if(!log_set && old_log_name != log_name) {
3890new_log_name = log_name;
3904 ctx.SetOldPostFormat(
false);
3920 if(log_set && new_handler && new_handler->
GetLogName() == old_log_name) {
3928 if( log_set && new_handler ) {
3929 ctx.FlushMessages(*new_handler);
3935 if( log_set && new_handler ) {
3936 ctx.FlushMessages(*new_handler);
3940 ctx.DiscardMessages();
3944 ctx.ResetLogRates();
3954s_ProcessPostCount.
Add(1) : s_ProcessPostCount.
Get());
3984 returns_DiagContext.
Get();
3991 #ifdef NCBI_LOG_FIELDS_CUSTOM 3995 typedef NCBI_PARAM_TYPE(Log, Ncbi_Log_Fields_Custom) TCustomLogFields;
4009 #ifdef NCBI_LOG_FIELDS_CUSTOM 4010 stringcustom_fields = TCustomLogFields::GetDefault();
4026 if( it->empty() )
continue;
4067 returnsx_GetPostFlags();
4073 boolCDiagBuffer::sm_IgnoreToDie =
false;
4077 boolCDiagBuffer::sm_TraceEnabled;
4080 const char* CDiagBuffer::sm_SeverityName[
eDiag_Trace+1] = {
4081 "Info",
"Warning",
"Error",
"Critical",
"Fatal",
"Trace"};
4099DEBUG_STACK_TRACE_LEVEL);
4106 static bools_DiagInitialized =
false;
4107 if(!s_DiagInitialized) {
4109 #ifdef NCBI_OS_MSWIN 4117s_DiagInitialized =
true;
4138 boolCDiagBuffer::sm_CanDeleteHandler =
true;
4140 boolCDiagBuffer::sm_CanDeleteErrCodeInfo =
false;
4146 static bools_DefaultDiagHandlerInitialized =
false;
4147 if( !s_DefaultDiagHandlerInitialized ) {
4148s_DefaultDiagHandlerInitialized =
true;
4150 if( TTeeToStderr::GetDefault() ) {
4174CDiagBuffer::CDiagBuffer(
void)
4176m_InitialStreamFlags(m_Stream->
flags()),
4182CDiagBuffer::~CDiagBuffer(
void)
4185 if(m_Diag || m_Stream->pcount())
4200 if( CDiagBuffer::sm_Handler ) {
4202 if( CDiagBuffer::sm_Handler ) {
4205 boolshow_warning =
false;
4208mess.
m_Prefix= diag_buf.m_PostPrefix.empty() ?
42090 : diag_buf.m_PostPrefix.c_str();
4217 if(
ctx.ApproveMessage(mess, &show_warning) ) {
4239CDiagBuffer::sm_Handler->
Post(phid_msg);
4241CDiagBuffer::sm_Handler->
Post(mess);
4243span->PostEvent(mess);
4246 else if( show_warning ) {
4250 stringlimit_name =
"error";
4254limit_name =
"applog";
4259limit_name =
"trace";
4262 stringtxt =
"Maximum logging rate for "+ limit_name +
" (" 4266+
" sec) exceeded, suspending the output.";
4269txt.c_str(), txt.length(),
4274err_code_x::eErrCodeX_Corelib_Diag,
4280CDiagBuffer::sm_Handler->
Post(err_msg);
4290 boolCDiagBuffer::SeverityDisabled(
EDiagSevsev)
4296 boolallow_trace = GetTraceEnabled();
4307 return(sev < post_sev) && (sev < sm_DieSeverity || sm_IgnoreToDie);
4312 boolCDiagBuffer::SeverityPrintable(
EDiagSevsev)
4318 boolallow_trace = GetTraceEnabled();
4329 return!((sev < post_sev) && (sev < sm_DieSeverity || sm_IgnoreToDie));
4333 boolCDiagBuffer::SetDiag(
const CNcbiDiag& diag)
4335 if( m_InUse || !m_Stream ) {
4341 if(!is_console && SeverityDisabled(sev)) {
4345 if(m_Diag != &diag) {
4368 static bool Check();
4383 #ifndef NCBI_THREADS 4384thread::id stored_thread_id;
4385thread::id this_thread_id = this_thread::get_id();
4388 if(
sm_ThreadID.compare_exchange_strong(stored_thread_id, this_thread_id))
return false;
4391 if(stored_thread_id == this_thread_id)
return false;
4393 boolreported =
false;
4396 if(
sm_Reported.compare_exchange_strong(reported,
true))
return true;
4411 const auto msg=
"Detected different threads using C++ Toolkit built in single thread mode."sv;
4430 voidCDiagBuffer::Flush(
void)
4432 if( m_InUse || !m_Diag ) {
4433 if( !m_InUse && m_Stream && !
IsOssEmpty(*m_Stream) ) {
4436m_Stream->rdbuf()->PUBSEEKOFF(0, IOS_BASE::beg,
IOS_BASE::out);
4443 EDiagSevsev = m_Diag->GetSeverity();
4444 boolis_console = (m_Diag->GetPostFlags() &
eDPF_IsConsole) != 0;
4445 boolis_disabled = SeverityDisabled(sev);
4448 if(!is_console && is_disabled) {
4456 flags|= sm_TraceFlags;
4463 if( m_Diag->CheckFilters() ) {
4469m_Diag->GetErrorCode(),
4470m_Diag->GetErrorSubCode(),
4472m_Diag->GetModule(),
4474m_Diag->GetFunction());
4475PrintMessage(mess, *m_Diag);
4481PrintMessage(mess, *m_Diag);
4484 #if defined(NCBI_COMPILER_KCC) 4491m_Stream->flags(m_InitialStreamFlags);
4492 # ifdef NCBI_SHUN_OSTRSTREAM 4500 if(sev >= sm_DieSeverity && sev !=
eDiag_Trace&& !sm_IgnoreToDie) {
4503 #ifdef NCBI_COMPILER_MSVC 4505 intold_mode = _set_error_mode(_OUT_TO_MSGBOX);
4507_set_error_mode(old_mode);
4522 if(!SeverityPrintable(sev)) {
4527 boolis_disabled = SeverityDisabled(sev);
4528 if(!is_disabled || (is_console && can_collect)) {
4545 boolCDiagBuffer::GetTraceEnabledFirstTime(
void)
4554sm_TraceEnabled = (sm_TraceDefault ==
eDT_Enable);
4555 returnsm_TraceEnabled;
4559 boolCDiagBuffer::GetSeverityChangeEnabledFirstTime(
void)
4575 voidCDiagBuffer::UpdatePrefix(
void)
4577m_PostPrefix.erase();
4578 ITERATE(TPrefixList, prefix, m_PrefixList) {
4579 if(prefix != m_PrefixList.begin()) {
4580m_PostPrefix +=
"::";
4582m_PostPrefix += *prefix;
4592 const char*
buf,
size_t len,
4593 const char*
file,
size_tline,
4595 interr_code,
interr_subcode,
4596 const char* err_text,
4597 const char* module,
4598 const char* nclass,
4599 const char*
function)
4600: m_Event(eEvent_Start),
4601m_TypedExtra(
false),
4603m_PrintStackTrace(
false),
4605m_Format(eFormat_Auto),
4606m_AllowBadExtraNames(
false)
4628 switch(app_state) {
4664m_Event(eEvent_Start),
4665m_TypedExtra(
false),
4667m_PrintStackTrace(
false),
4669m_Format(eFormat_Auto),
4670m_AllowBadExtraNames(
false)
4706m_Event(eEvent_Start),
4707m_TypedExtra(
false),
4709m_PrintStackTrace(
false),
4711m_Format(eFormat_Auto),
4712m_AllowBadExtraNames(
false)
4720 if(&message !=
this) {
4790 if(pos >= message.length()) {
4792 "Failed to parse diagnostic message");
4796 if(message[pos + width] != sep) {
4798 "Missing separator after integer");
4802width = message.find(sep, pos);
4803 if(width ==
NPOS) {
4805 "Missing separator after integer");
4819 booloptional =
false)
4821 if(pos >= message.length()) {
4823 "Failed to parse diagnostic message");
4826pos = message.find(sep, pos1);
4830 "Failed to parse diagnostic message");
4835 if( pos == pos1 + 1 && !optional ) {
4838 "Failed to parse diagnostic message");
4842pos = message.find_first_not_of(sep, pos);
4844pos = message.length();
4846 return CTempString(message.c_str() + pos1, pos2 - pos1);
4851 "%00",
"%01",
"%02",
"%03",
"%04",
"%05",
"%06",
"%07",
4852 "%08",
"%09",
"%0A",
"%0B",
"%0C",
"%0D",
"%0E",
"%0F",
4853 "%10",
"%11",
"%12",
"%13",
"%14",
"%15",
"%16",
"%17",
4854 "%18",
"%19",
"%1A",
"%1B",
"%1C",
"%1D",
"%1E",
"%1F",
4855 "+",
"!",
"\"",
"#",
"$",
"%25",
"%26",
"'",
4856 "(",
")",
"*",
"%2B",
",",
"-",
".",
"/",
4857 "0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
4858 "8",
"9",
":",
";",
"<",
"%3D",
">",
"?",
4859 "@",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
4860 "H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
4861 "P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
4862 "X",
"Y",
"Z",
"[",
"\\",
"]",
"^",
"_",
4863 "`",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
4864 "h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
4865 "p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
4866 "x",
"y",
"z",
"{",
"|",
"}",
"~",
"%7F",
4867 "%80",
"%81",
"%82",
"%83",
"%84",
"%85",
"%86",
"%87",
4868 "%88",
"%89",
"%8A",
"%8B",
"%8C",
"%8D",
"%8E",
"%8F",
4869 "%90",
"%91",
"%92",
"%93",
"%94",
"%95",
"%96",
"%97",
4870 "%98",
"%99",
"%9A",
"%9B",
"%9C",
"%9D",
"%9E",
"%9F",
4871 "%A0",
"%A1",
"%A2",
"%A3",
"%A4",
"%A5",
"%A6",
"%A7",
4872 "%A8",
"%A9",
"%AA",
"%AB",
"%AC",
"%AD",
"%AE",
"%AF",
4873 "%B0",
"%B1",
"%B2",
"%B3",
"%B4",
"%B5",
"%B6",
"%B7",
4874 "%B8",
"%B9",
"%BA",
"%BB",
"%BC",
"%BD",
"%BE",
"%BF",
4875 "%C0",
"%C1",
"%C2",
"%C3",
"%C4",
"%C5",
"%C6",
"%C7",
4876 "%C8",
"%C9",
"%CA",
"%CB",
"%CC",
"%CD",
"%CE",
"%CF",
4877 "%D0",
"%D1",
"%D2",
"%D3",
"%D4",
"%D5",
"%D6",
"%D7",
4878 "%D8",
"%D9",
"%DA",
"%DB",
"%DC",
"%DD",
"%DE",
"%DF",
4879 "%E0",
"%E1",
"%E2",
"%E3",
"%E4",
"%E5",
"%E6",
"%E7",
4880 "%E8",
"%E9",
"%EA",
"%EB",
"%EC",
"%ED",
"%EE",
"%EF",
4881 "%F0",
"%F1",
"%F2",
"%F3",
"%F4",
"%F5",
"%F6",
"%F7",
4882 "%F8",
"%F9",
"%FA",
"%FB",
"%FC",
"%FD",
"%FE",
"%FF" 4904 size_t len=
str.length();
4907 "Empty name in extra-arg", 0);
4911 for(
size_tp = 0; p <
len; dst++) {
4912 switch(
str[p] ) {
4916 "Inavild char in extra arg", p);
4920 if(n1 < 0 || n2 < 0) {
4922 "Inavild char in extra arg", p);
4924 str[dst] = char((n1 << 4) | n2);
4936 "Unencoded special char in extra arg", p);
4951 if(
str.find(
'&', pos) ==
NPOS&&
str.find(
'=', pos) ==
NPOS) {
5018 size_tsl_pos = message.find(
'/', pos);
5019 size_tsp_pos = message.find(
' ', pos);
5020 if(sl_pos < sp_pos) {
5044 static const char* s_TimeFormats[4] = {
5047 if(
tmp.find(
'T') ==
NPOS) {
5050 else if(
tmp.find(
'.') ==
NPOS) {
5084 boolhave_severity =
false;
5085 size_tseverity_pos = pos;
5087 if( !
tmp.empty() ) {
5089 size_tsev_pos =
NPOS;
5090 if(
tmp.length() == 10 &&
tmp.find(
"Message[") == 0) {
5093 else if(
tmp.length() == 7 &&
tmp.find(
"Note[") == 0) {
5097 if(sev_pos !=
NPOS) {
5099 switch(
tmp[sev_pos] ) {
5122have_severity =
true;
5129 if( have_severity ) {
5130pos = message.find_first_not_of(
' ', pos);
5132pos = message.length();
5139 if(
tmp.empty() && severity_pos < message.length()) {
5141pos = message.length();
5151 if(pos < message.length()) {
5153pos = message.length();
5162 if(pos < message.length()) {
5164pos = message.length();
5170 if(pos < message.length()) {
5173 size_tmsg_end = message.find_first_not_of(
' ', pos);
5174msg_end = message.find_first_of(
' ', msg_end);
5175msg_end = message.find_first_not_of(
' ', msg_end);
5176msg_end = message.find_first_of(
' ', msg_end);
5177 size_textra_pos = message.find_first_not_of(
' ', msg_end);
5179substr(0, msg_end - pos);
5184pos = message.length();
5193 if(pos < message.length()) {
5204 size_tsep_pos = message.find(
" --- ", pos);
5207 if(pos < sep_pos && message[pos] !=
'"') {
5208 size_tmod_pos = pos;
5210 size_t lbr=
tmp.find(
"(");
5212 if(
tmp[
tmp.length() - 1] !=
')') {
5215 while(open_br > 0 && pos < message.length()) {
5216 if(message[pos] ==
'(') {
5219 else if(message[pos] ==
')') {
5224 if(message[pos] !=
' '|| pos >= message.length()) {
5229pos = message.find_first_not_of(
' ', pos);
5231pos = message.length();
5236 size_tdot_pos =
tmp.find(
'.');
5237 if(dot_pos !=
NPOS) {
5262 if(pos < sep_pos && message[pos] ==
'"') {
5268 if(
CTempString(message.c_str() + pos, 7) !=
", line ") {
5273pos = message.find_first_not_of(
' ', pos);
5275pos = message.length();
5279 if(pos < sep_pos) {
5281 if(message.find(
"::", pos) !=
NPOS) {
5282 size_ttmp_pos = sep_pos;
5283 while(tmp_pos > pos && message[tmp_pos - 1] ==
' ')
5285 tmp.assign(message.data() + pos, tmp_pos - pos);
5286 size_tdcol =
tmp.find(
"::");
5287 if(dcol ==
NPOS) {
5288 gotoparse_unk_func;
5297 if(dcol <
tmp.length() - 2) {
5299 if(
tmp[
tmp.length() - 2] !=
'('||
tmp[
tmp.length() - 1] !=
')') {
5303 tmp.length() - dcol - 2);
5310 size_tunkf = message.find(
"UNK_FUNC", pos);
5317 if(
CTempString(message.c_str() + pos, 4) ==
"--- ") {
5341 stringmsg_str, line, last_msg_str;
5343unique_ptr<SDiagMessage>
msg;
5344unique_ptr<SDiagMessage> last_msg;
5345 while(
in.good() ) {
5346getline(
in, line);
5348 if(line.size() < 15) {
5349 if( !line.empty() ) {
5350msg_str +=
"\n"+ line;
5356 for(
size_t i= 0;
i< 15;
i++) {
5357 if(line[
i] !=
'/'&& (line[
i] <
'0'|| line[
i] >
'9')) {
5359msg_str +=
"\n"+ line;
5364 if( line.empty() ) {
5368 if( msg_str.empty() ) {
5374 if( last_msg.get() ) {
5377last_msg_str = msg_str;
5378last_msg.reset(
msg.release());
5380 else if( !last_msg_str.empty() ) {
5381last_msg_str +=
"\n"+ msg_str;
5382last_msg.reset(
new SDiagMessage(last_msg_str, &res));
5385 Error<<
"Failed to parse message: "<< last_msg_str);
5393 if( !msg_str.empty() ) {
5396 if( last_msg.get() ) {
5401 else if( !last_msg_str.empty() ) {
5402last_msg_str +=
"\n"+ msg_str;
5409 Error<<
"Failed to parse message: "<< last_msg_str);
5414 Error<<
"Failed to parse message: "<< msg_str);
5430 return "request-start";
5432 return "request-stop";
5469TDiagWriteFlags
flags)
const 5490 const char* mod_start = 0;
5491 const char* mod_end =
m_File;
5492 const char* c = strchr(
m_File, sep_chr);
5495mod_start = mod_end;
5498c = strchr(c + 1, sep_chr);
5503 while(*mod_start == sep_chr) {
5506 if(mod_end < mod_start + 1) {
5509 stringret(mod_start, mod_end - mod_start);
5518 CExtraEncoder(
boolallow_bad_names =
false) : m_AllowBadNames(allow_bad_names) {}
5529 static const char* s_BadSymbolPrefix =
"[INVALID_APPLOG_SYMBOL:";
5530 static const char* s_BadSymbolSuffix =
"]";
5531 static const size_ts_BadSymbolPrefixLen = strlen(s_BadSymbolPrefix);
5534vector<CTempString> parts;
5535parts.resize(src.
length() + 2);
5536 size_tpart_idx = 0;
5537 const char* src_data = src.
data();
5539 size_tgood_start = 0;
5540 size_ttotal_len = 0;
5541 for(
size_tpos = 0; pos < src.
size(); ++pos) {
5544 if(enc[0] == c && enc[1] == 0)
continue;
5547 if(good_start < pos) {
5549good_part.
assign(src_data + good_start, pos - good_start);
5550total_len += good_part.
size();
5553 if(warn_bad_name) {
5555warn_part.
assign(s_BadSymbolPrefix, s_BadSymbolPrefixLen);
5556total_len += s_BadSymbolPrefixLen;
5559enc_part.
assign((c ==
' '&& warn_bad_name) ? s_EncodedSpace : enc);
5560total_len += enc_part.
size();
5561 if(warn_bad_name) {
5563warn2_part.
assign(s_BadSymbolSuffix, 1);
5566good_start = pos + 1;
5568 if(part_idx + 3 >= parts.size()) parts.resize(parts.size() * 2);
5571 if(good_start < src.
size()) {
5573good_part.
assign(src_data + good_start, src.
size() - good_start);
5574total_len += good_part.
size();
5577 char*
buf=
new char[total_len];
5579 for(
size_t i= 0;
i< part_idx; ++
i) {
5581strncpy(pos, part.
data(), part.
size());
5582pos += part.
size();
5584 stringret(
buf, total_len);
5603 size_tp =
buf.find_first_of(
"\n\v\377");
5604 if(p ==
NPOS)
return;
5605 for(; p <
buf.size(); p++) {
5609 buf.insert(p, 1,
'\377');
5622 if(
buf.find_first_of(
"\v\377") ==
NPOS)
return;
5623 size_tsrc = 0, dst = 0;
5624 for(; src <
buf.size(); src++, dst++) {
5625 switch(
buf[src]) {
5627 if(src <
buf.size() - 1 &&
5628(
buf[src + 1] ==
'\377'||
buf[src + 1] ==
'\v')) {
5668 stringold_prefix =
trace.GetPrefix();
5669 trace.SetPrefix(
" ");
5670os <<
"\n Stack trace:\n"<<
trace;
5671 trace.SetPrefix(old_prefix);
5696 const char* x_file =
m_File;
5698 for(
const char* s =
m_File; *s; s++) {
5699 if(*s ==
'/'|| *s ==
'\\'|| *s ==
':')
5703os <<
'"'<< x_file <<
'"';
5709os << (print_file ?
", line ":
"line ") <<
m_Line;
5712 if(print_file || print_line)
5716 boolhave_description =
false;
5728have_description =
true;
5740os <<
"Note["<< sev[0] <<
"]";
5762 boolprint_location =
5768 boolneed_separator =
false;
5769 if(print_location) {
5773 boolneed_double_colon =
false;
5775 if( have_module ) {
5777need_double_colon =
true;
5781 if(need_double_colon)
5784need_double_colon =
true;
5788 if(need_double_colon)
5790need_double_colon =
false;
5794 if( need_double_colon )
5798need_separator =
true;
5802 if(err_text_prefix && have_description &&
5805os <<
"{"<< description.
m_Message<<
"} ";
5806need_separator =
true;
5809 if(need_separator) {
5822 if(have_description) {
5823 if(!err_text_prefix &&
5836 string buf= os.str();
5839 switch(s_DiagMergeLines->
Get()) {
5841merge_lines =
true;
5844merge_lines =
false;
5876 boolhave_description =
false;
5886have_description =
true;
5894os << setfill(
' ') << setw(13) << setiosflags(IOS_BASE::left)
5900os << setfill(
' ') << setw(13)
5901<< setiosflags(IOS_BASE::left) << setw(0);
5903os <<
"Note["<< sev[0] <<
"]:";
5908os << resetiosflags(IOS_BASE::left);
5917os << (have_module ?
x_GetModule() :
"UNK_MODULE");
5932 const char* x_file =
m_File;
5934 for(
const char* s =
m_File; *s; s++) {
5935 if(*s ==
'/'|| *s ==
'\\'|| *s ==
':')
5939os <<
'"'<< x_file <<
'"';
5942os <<
"\"UNK_FILE\"";
5945os <<
", line "<<
m_Line;
5989 if(have_description) {
5992os <<
'\n'<< description.
m_Message<<
' ';
6002 string buf= os.str();
6006 if(max_len > 0 &&
buf.size() > max_len) {
6007 buf.resize(max_len);
6142new_flags |= prev_flags;
6206 buf.m_PostPrefix = prefix;
6208 buf.m_PostPrefix.erase();
6210 buf.m_PrefixList.clear();
6216 if(prefix && *prefix) {
6218 buf.m_PrefixList.push_back(prefix);
6219 buf.UpdatePrefix();
6227 if( !
buf.m_PrefixList.empty() ) {
6228 buf.m_PrefixList.pop_back();
6229 buf.UpdatePrefix();
6236 if(post_sev < eDiagSevMin || post_sev >
eDiagSevMax) {
6238 "SetDiagPostLevel() -- Severity must be in the range " 6239 "[eDiagSevMin..eDiagSevMax]");
6243 EDiagSevsev = CDiagBuffer::sm_PostSeverity;
6250CDiagBuffer::sm_PostSeverity = post_sev;
6258 returnCDiagBuffer::sm_PostSeverity;
6264 if(sev1 == sev2)
return0;
6274 returnCDiagBuffer::GetTraceEnabled();
6294 boolprev_status = (CDiagBuffer::sm_PostSeverityChange ==
eDiagSC_Enable);
6295CDiagBuffer::sm_PostSeverityChange = disable_change ?
eDiagSC_Disable:
6303 if(die_sev < eDiagSevMin || die_sev >
eDiag_Fatal) {
6305 "SetDiagDieLevel() -- Severity must be in the range " 6306 "[eDiagSevMin..eDiag_Fatal]");
6310 EDiagSevsev = CDiagBuffer::sm_DieSeverity;
6311CDiagBuffer::sm_DieSeverity = die_sev;
6318 returnCDiagBuffer::sm_DieSeverity;
6325 boolretval = CDiagBuffer::sm_IgnoreToDie;
6326CDiagBuffer::sm_IgnoreToDie = ignore;
6334(void) CDiagBuffer::GetTraceEnabled();
6337CDiagBuffer::sm_TraceDefault = dflt;
6340how = CDiagBuffer::sm_TraceDefault;
6341CDiagBuffer::sm_TraceEnabled = (how ==
eDT_Enable);
6347 returnCDiagBuffer::GetTraceEnabled();
6384stringstream str_os;
6387 string str= str_os.str();
6388cerr.write(
str.data(),
str.size());
6397 boolreport_switch =
ctx.IsSetOldPostFormat() &&
6399 stringold_name, new_name;
6401 if( CDiagBuffer::sm_Handler ) {
6402old_name = CDiagBuffer::sm_Handler->
GetLogName();
6405new_name =
handler->GetLogName();
6406 if(report_switch && new_name != old_name) {
6407 ctx.Extra().Print(
"switch_diag_to", new_name);
6412 if(CDiagBuffer::sm_CanDeleteHandler && CDiagBuffer::sm_Handler !=
handler)
6413 deleteCDiagBuffer::sm_Handler;
6414 if( TTeeToStderr::GetDefault() ) {
6419CDiagBuffer::sm_Handler =
handler;
6420CDiagBuffer::sm_CanDeleteHandler = can_delete;
6421 if(report_switch && !old_name.empty() && new_name != old_name) {
6422 ctx.Extra().Print(
"switch_diag_from", old_name);
6435 bool* current_ownership)
6438 if( current_ownership ) {
6439*current_ownership = CDiagBuffer::sm_CanDeleteHandler;
6441 if(take_ownership) {
6442 _ASSERT(CDiagBuffer::sm_CanDeleteHandler);
6443CDiagBuffer::sm_CanDeleteHandler =
false;
6445 returnCDiagBuffer::sm_Handler;
6472stringstream str_os;
6474 string str= str_os.str();
6475cerr.write(
str.data(),
str.size());
6482 stringname =
typeid(*this).name();
6529 const string& stream_name)
6531m_QuickFlush(quick_flush)
6533 if( !stream_name.empty() ) {
6547stringstream str_os;
6549 string str= str_os.str();
6562 #if defined(NCBI_OS_MSWIN) 6563 int mode= O_WRONLY | O_APPEND | O_CREAT | O_BINARY | O_NOINHERIT;
6565 int mode= O_WRONLY | O_APPEND | O_CREAT;
6580 #if defined(NCBI_OS_UNIX) 6597m_HavePosts(
false),
6598m_LowDiskSpace(
false),
6649 if(limit > 0 && pos > limit) {
6702 if(it->m_PID != pid) {
6775stringstream str_os;
6777 returnstr_os.str();
6826|| name ==
"/dev/null" 6827|| name ==
"/dev/stdout" 6828|| name ==
"/dev/stderr";
6838m_OwnTrace(
false),
6868 if(!ptr || !(*ptr)) {
6910*own_member =
false;
6917 if(member != &
m_Err) {
6922 if(member != &
m_Log) {
6932 if(member != &
m_Perf) {
6968unique_ptr<CStreamDiagHandler_Base>&
handler,
6971 if( fname.empty() || fname ==
"/dev/null") {
6975 if(fname ==
"-") {
6980 if( !fh->Valid() ) {
6994unique_ptr<CStreamDiagHandler_Base>
err_handler, log_handler,
6995trace_handler, perf_handler;
7003 stringext = entry.
GetExt();
7004 if(ext ==
".log"||
7011 stringerr_name = special ? adj_name : adj_name +
".err";
7012 stringlog_name = special ? adj_name : adj_name +
".log";
7013 stringtrace_name = special ? adj_name : adj_name +
".trace";
7014 stringperf_name = special ? adj_name : adj_name +
".perf";
7179 switch(
msg.m_Severity ) {
7287 virtual void*
Main(
void);
7295 #ifdef NCBI_HAVE_CONDITIONAL_VARIABLE 7311DIAG_MAX_ASYNC_QUEUE_SIZE);
7315: m_AsyncThread(
NULL)
7376 if(
thr->m_SubHandler->AllowAsyncWrite(mess)) {
7387 while(
Uint4(
thr->m_MsgsInQueue.Get()) >= s_MaxAsyncQueueSizeParam->
Get())
7389++
thr->m_CntWaiters;
7390 #ifdef NCBI_HAVE_CONDITIONAL_VARIABLE 7391 thr->m_DequeueCond.WaitForSignal(
thr->m_QueueLock);
7394 thr->m_QueueSem.Wait();
7397--
thr->m_CntWaiters;
7399 thr->m_MsgQueue.push_back(async);
7400 if(
thr->m_MsgsInQueue.Add(1) == 1) {
7401 #ifdef NCBI_HAVE_CONDITIONAL_VARIABLE 7402 thr->m_QueueCond.SignalSome();
7404 thr->m_QueueSem.Post();
7410 thr->m_SubHandler->Post(mess);
7418: m_NeedStop(
false),
7420m_SubHandler(
NULL),
7423m_DequeueSem(0, 10000000),
7425m_ThreadSuffix(thread_suffix)
7452:
data(0),
size(0), pos(0), lines(0)
7458max_lines =
NCBI_PARAM_TYPE(Diag, Async_Buffer_Max_Lines)::GetDefault();
7481 if(!
size|| pos +
str.size() >=
size|| lines >= max_lines) {
7484memcpy(&
data[pos],
str.data(),
str.size());
7496DIAG_ASYNC_BATCH_SIZE);
7509 const intbatch_size =
NCBI_PARAM_TYPE(Diag, Async_Batch_Size)::GetDefault();
7513 for(
size_t i= 0;
i< buf_count; ++
i) {
7517deque<SAsyncDiagMessage> save_msgs;
7524 #ifdef NCBI_HAVE_CONDITIONAL_VARIABLE 7536 intqueue_counter = 0;
7537 while(!save_msgs.empty()) {
7539save_msgs.pop_front();
7540 if(
msg.m_Composed ) {
7544buffers[
msg.m_FileType] =
buf;
7546 if( !
buf->size ) {
7549 msg.m_Composed->size(),
msg.m_FileType);
7551 else if( !
buf->Append(*
msg.m_Composed) ) {
7554 if( !
buf->IsEmpty() ) {
7558 if( !
buf->Append(*
msg.m_Composed) ) {
7561 msg.m_Composed->size(),
msg.m_FileType);
7564 delete msg.m_Composed;
7569 delete msg.m_Message;
7571 if(++queue_counter >= batch_size || save_msgs.empty()) {
7575 #ifdef NCBI_HAVE_CONDITIONAL_VARIABLE 7576m_DequeueCond.SignalSome();
7585 for(
size_t i= 0;
i< buf_count; ++
i) {
7586 if( !buffers[
i] ) {
7589 if( !buffers[
i]->IsEmpty() ) {
7599 gotodrain_messages;
7602 for(
size_t i= 0;
i< buf_count; ++
i) {
7603 if( !buffers[
i] ) {
7606 if( !buffers[
i]->IsEmpty() ) {
7610 deletebuffers[
i];
7621 #ifdef NCBI_HAVE_CONDITIONAL_VARIABLE 7622m_QueueCond.SignalAll();
7630<<
"Error while stopping thread for AsyncDiagHandler: "<< ex);
7642 if( !dir.empty() && !
CDir(dir).Exists() ) {
7654 "Failed to set log file for the selected event type: " 7655 "split log is disabled");
7681 boolold_ownership =
false;
7684 if( !sub_handler ) {
7685old_ownership =
false;
7691 if( old_ownership ) {
7695fhandler->SetSubHandler(sub_handler,
eDiagFile_All, old_ownership);
7705 if( old_ownership ) {
7747 return(sdh && sdh->
GetStream() == os);
7754 if( CDiagBuffer::sm_CanDeleteErrCodeInfo &&
7755CDiagBuffer::sm_ErrCodeInfo )
7756 deleteCDiagBuffer::sm_ErrCodeInfo;
7757CDiagBuffer::sm_ErrCodeInfo =
info;
7758CDiagBuffer::sm_CanDeleteErrCodeInfo = can_delete;
7763 return(CDiagBuffer::sm_ErrCodeInfo != 0);
7769 if(take_ownership) {
7770 _ASSERT(CDiagBuffer::sm_CanDeleteErrCodeInfo);
7771CDiagBuffer::sm_CanDeleteErrCodeInfo =
false;
7773 returnCDiagBuffer::sm_ErrCodeInfo;
7821m_PostFlags(ForceImportantFlags(post_flags)),
7822m_OmitStackTrace(
false)
7833m_PostFlags(ForceImportantFlags(post_flags)),
7834m_OmitStackTrace(
false),
7835m_CompileInfo(
info)
7900 if( !stacktrace.
Empty() ) {
7915 strings = os.str();
7940stack<const CException*> pile;
7948main_pex = pile.top();
7950*
this<<
"("<< main_pex->
GetType() <<
"::" 7955*
this<< main_pex->
GetType() <<
"::" 7959 for(; !pile.empty(); pile.pop()) {
7969 stringerr_type(pex->
GetType());
7976pex_sev = collect_sev;
7980pex_sev = print_sev;
8004 m_Buffer.PrintMessage(diagmsg, *
this);
8013 if(!str_sev || !*str_sev) {
8021}
else if( nsev == -1 ) {
8037 const char* message)
8046 const char* message)
8052 const char* expression,
8053 const char* message)
8056 "Assertion failed: ("<<
8057(expression ? expression :
"") <<
") "<<
8058(message ? message :
"") <<
Endm;
8064 const char* expression,
8065 const char* message)
8074 const char* message)
8107 buf.sm_CanDeleteHandler =
false;
8108 buf.sm_CanDeleteErrCodeInfo =
false;
8139: m_Func(func), m_Data(
data), m_Cleanup(
cleanup)
8168 boolquick_flush =
true,
8170 void* cleanup_data = 0,
8171 const string& stream_name =
kEmptyStr)
8173m_Cleanup(
cleanup), m_CleanupData(cleanup_data)
8180m_Cleanup(m_CleanupData);
8193 void* cleanup_data,
8194 const string& stream_name)
8196 stringstr_name = stream_name;
8197 if( str_name.empty() ) {
8201 else if(os == &cout) {
8238 ERR_POST_X(10,
Error<<
"SetDoubleDiagHandler() is not implemented");
8314list<string> tokens;
8329 if(tokens.size() < 2) {
8330 ERR_POST_X(11,
"Error message file parsing: Incorrect file format " 8343 if( !tokens.empty() ) {
8350 "Incorrect severity level in the verbose " 8371 boolerr_ready =
false;
8373 interr_subcode = 0;
8376 interr_severity = -1;
8378 interr_subseverity = -1;
8388 if(err_ready &&
str[0] ==
'$') {
8389 if(err_subseverity == -1)
8390err_subseverity = err_severity;
8395err_subseverity = -1;
8403err_message, err_ready))
8410err_message, err_ready);
8412}
else if(err_ready) {
8414 if(!err_text.empty()) {
8421 if(err_subseverity == -1)
8422err_subseverity = err_severity;
8442*description = entry;
ncbi::TMaskedQueryRegions mask
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)
static void Register(CSafeStaticPtr_Base *ptr)
Add new on-demand variable to the cleanup stack.
T & Get(void)
Create the variable if not created yet, return the reference.
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
int Main(int argc, const char *argv[])
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_ErrCode
Error code.
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.
static bool GetDisabledAppLog(void)
Get flag disabling applog events (set by DIAG_DISABLE_APPLOG_MESSAGES variable).
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.
bool GetDisabledAppLog(void) const
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)
shared_ptr< ITracerSpan > GetTracerSpan(void) const
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.
CDiagContext::EDisabledAppLogEvents GetDisabledAppLogEvents(void) const
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.
EDisabledAppLogEvents
Flags for disabling groups of applog events with DIAG_DISABLE_APPLOG_MESSAGES.
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
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.
static EDisabledAppLogEvents GetDisabledAppLogEvents(void)
Get disabled applog events (set by DIAG_DISABLE_APPLOG_MESSAGE_TYPES variable).
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.
@ fNoEndl
No end of line.
@ 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_Err
Error log.
@ 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).
@ eDisable_All
Disable all applog events (default).
@ eEnable_App
Allow only application start/stop.
@ 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_AppRun
A.
@ 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 whitespace 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 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)
void Check(const string &value)
const struct ncbi::grid::netcache::search::fields::SIZE size
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_IsDisabledAppLogEvent(const CRequestContext &rctx, SDiagMessage::EEventType event_type)
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 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
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_)
Defines CRequestContext class for NCBI C++ diagnostic API.
static SLJIT_INLINE sljit_ins st(sljit_gpr r, sljit_s32 d, sljit_gpr x, sljit_gpr b)
static SLJIT_INLINE sljit_ins lbr(sljit_gpr dst, sljit_gpr src)
static SLJIT_INLINE sljit_ins msg(sljit_gpr r, sljit_s32 d, sljit_gpr x, sljit_gpr b)
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]
void Encode(const CRawScoreVector< Key, Score > &, vector< char > &)
void Decode(const vector< char > &, CRawScoreVector< Key, Score > &)
static wxAcceleratorEntry entries[3]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4