8#if !defined(ALIB_C20_MODULES) || ((ALIB_C20_MODULES != 0) && (ALIB_C20_MODULES != 1))
9# error "Symbol ALIB_C20_MODULES has to be given to the compiler as either 0 or 1"
55 Formatters.emplace_back( firstLevelFormatter );
62 "ALox object converter recursion counter > 0.\n"
63 "Note: This error indicates, that a previous format operation (log statement) contained\n"
64 " corrupt format values, which caused the formatter to behave undefined, including\n"
65 " the corruption of the execution stack of ALox logging." )
76 // get a formatter. We use a clone per recursion depth!
77 // So, did we have this depth already before? If not, create a new set of formatters formatter
78 if( size_t( cntRecursion ) >= Formatters.size() )
80 // create a pair of recursion formatters
81 Formatter* recursionFormatter= new FormatterPythonStyle();
82 recursionFormatter->Next.InsertDerived<FormatterJavaStyle>();
83 recursionFormatter->CloneSettings( *Formatters[0] );
84 Formatters.emplace_back( recursionFormatter );
87 Formatter* formatter= Formatters[size_t( cntRecursion )];
91 formatter->FormatArgs( target, logables );
95 target << ALOX.GetResource("TLFmtExc
");
96 ALIB_LOCK_RECURSIVE_WITH( format::Formatter::DefaultLock )
103void StandardConverter::SetAutoSizes( AutoSizes* autoSizes )
105 FormatterPythonStyle* fmtPS= dynamic_cast<FormatterPythonStyle*>( Formatters[0] );
106 if (fmtPS != nullptr )
107 fmtPS->Sizes= autoSizes;
110AutoSizes* StandardConverter::GetAutoSizes()
112 FormatterPythonStyle* fmtPS= dynamic_cast<FormatterPythonStyle*>( Formatters[0] );
113 if (fmtPS != nullptr )
118void StandardConverter::ResetAutoSizes()
120 FormatterPythonStyle* fmtPS;
121 for( auto* elem : Formatters )
122 if ( (fmtPS= dynamic_cast<FormatterPythonStyle*>( elem )) != nullptr )
123 fmtPS->Sizes->Reset();
126// #################################################################################################
128// #################################################################################################
129void TextLogger::writeMetaInfo( AString& buf, detail::Domain& domain, Verbosity verbosity,
130 detail::ScopeInfo& scope )
133 auto& fmt= varFormatMetaInfo.Get<FormatMetaInfo>();
134 if ( fmt.Format.IsEmpty() )
137 // clear DateTime singleton
138 callerDateTime.Year= (std::numeric_limits<int>::min)();
140 Substring format( fmt.Format );
143 // get next and log substring between commands
144 integer idx= format.IndexOf( '%' );
147 format.ConsumeChars<NC, lang::CurrentData::Keep>( idx, buf, 1 );
148 processVariable( domain.FullPath, verbosity, scope, buf, format );
158void TextLogger::processVariable( const NString& domainPath,
160 detail::ScopeInfo& scope,
162 Substring& variable )
166 auto& fmt= varFormatMetaInfo .Get<FormatMetaInfo>();
167 auto& autoSizes= varFormatAutoSizes.Get<FormatAutoSizes>();
169 switch ( variable.ConsumeChar() )
176 switch( c2= variable.ConsumeChar() )
178 case 'P': // SP: full path
180 val= scope.GetFullPath();
182 val= GetFormatOther().NoSourceFileInfo;
185 case 'p': // Sp: trimmed path
187 integer previousLength= dest.Length();
188 scope.GetTrimmedPath( dest );
189 if( dest.Length() != previousLength )
191 val= GetFormatOther().NoSourceFileInfo;
194 case 'F': // file name
196 val= scope.GetFileName();
198 val= GetFormatOther().NoSourceFileInfo;
201 case 'f': // file name without extension
203 val= scope.GetFileNameWithoutExtension();
205 val= GetFormatOther().NoSourceFileInfo;
209 case 'M': // method name
211 val= scope.GetMethod();
213 val= GetFormatOther().NoMethodInfo;
216 case 'L': // line number
218 dest._<NC>( scope.GetLineNumber() );
224 ALIB_ASSERT_WARNING( FormatWarningOnce, "ALOX",
225 "Unknown
format variable
'%S{}' (only one warning)
", c2 )
226 ALIB_DBG( FormatWarningOnce= true; )
237 c2= variable.ConsumeChar();
242 // get time stamp as CalendarDateTime once
243 if ( callerDateTime.Year == (std::numeric_limits<int>::min)() )
244 callerDateTime.Set( DateConverter.ToDateTime( scope.GetTimeStamp() ) );
246 // if standard format, just write it out
247 if ( GetFormatDate().Date.Equals<NC>( A_CHAR("yyyy-MM-dd
") ) )
249 dest._<NC>( alib::Dec( callerDateTime.Year, 4 ) )._<NC>( '-' )
250 ._<NC>( alib::Dec( callerDateTime.Month, 2 ) )._<NC>( '-' )
251 ._<NC>( alib::Dec( callerDateTime.Day, 2 ) );
253 // user-defined format
255 callerDateTime.Format( GetFormatDate().Date, dest );
264 // get time stamp as CalendarDateTime once
265 if ( callerDateTime.Year == (std::numeric_limits<int>::min)() )
266 callerDateTime.Set( DateConverter.ToDateTime( scope.GetTimeStamp() ) );
268 // avoid the allocation of a) a StringBuilder (yes, a string builder is allocated inside StringBuilder.AppendFormat!)
269 // and b) a DateTime object, if the format is the unchanged standard. And it is faster anyhow.
270 if ( GetFormatDate().TimeOfDay.Equals<NC>( A_CHAR("HH:mm:ss
") ) )
272 dest._<NC>( alib::Dec(callerDateTime.Hour, 2) )._<NC>( ':' )
273 ._<NC>( alib::Dec(callerDateTime.Minute, 2) )._<NC>( ':' )
274 ._<NC>( alib::Dec(callerDateTime.Second, 2) );
277 // user-defined format
279 callerDateTime.Format( GetFormatDate().TimeOfDay, dest );
282 // %TC: Time elapsed since created
283 else if ( c2 == 'C' )
285 auto elapsedTime= scope.GetTimeStamp() - TimeOfCreation;
286 auto elapsedSecs= elapsedTime.InAbsoluteSeconds();
287 CalendarDuration elapsed( elapsedTime );
289 // determine number of segments to write and match this to recent (autosizes) value
290 int timeSize= elapsedSecs >= 24*3600 ? 6
291 : elapsedSecs >= 10*3600 ? 5
292 : elapsedSecs >= 3600 ? 4
293 : elapsedSecs >= 10*60 ? 3
294 : elapsedSecs >= 60 ? 2
295 : elapsedSecs >= 9 ? 1
297 timeSize= int(autoSizes.Main.Next( AutoSizes::Types::Field, timeSize, 0 ));
300 if ( timeSize >= 4 ) dest._<NC>( elapsed.Days )._<NC>( GetFormatDate().ElapsedDays );
301 if ( timeSize >= 3 ) dest._<NC>( alib::Dec(elapsed.Hours , timeSize >= 5 ? 2 : 1 ) )._<NC>( ':' );
302 if ( timeSize >= 2 ) dest._<NC>( alib::Dec(elapsed.Minutes, timeSize >= 3 ? 2 : 1 ) )._<NC>( ':' );
303 dest._<NC>( alib::Dec(elapsed.Seconds, timeSize >= 1 ? 2 : 1) )._<NC>( '.' );
304 dest._<NC>( alib::Dec(elapsed.Milliseconds, 3) );
307 // %TL: Time elapsed since last log call
308 else if ( c2 == 'L' )
309 writeTimeDiff( dest, scope.GetTimeStamp().Since( TimeOfLastLog ).InNanoseconds() );
313 ALIB_ASSERT_WARNING( FormatWarningOnce, "ALOX",
314 "Unknown
format variable
'%T{}' (only one warning)
", c2 )
315 ALIB_DBG( FormatWarningOnce= true; )
324 c2= variable.ConsumeChar();
326 if ( c2 == 'N' ) // %tN: thread name
328 #if !ALIB_SINGLE_THREADED
329 const String& threadName= scope.GetThreadNameAndID(nullptr);
331 String msg( A_CHAR("SINGLE_THREADED
") );
332 const String& threadName= msg;
334 dest._<NC>( Field( threadName,
336 AutoSizes::Types::Field, threadName.Length(), 0),
337 lang::Alignment::Center ) );
339 else if ( c2 == 'I' ) // %tI: thread ID
342 #if !ALIB_SINGLE_THREADED
343 threadID._( scope.GetThreadID() );
347 dest._<NC>( Field( threadID,
349 AutoSizes::Types::Field, threadID .Length(), 0),
350 lang::Alignment::Center ) );
354 ALIB_ASSERT_WARNING( FormatWarningOnce, "ALOX",
355 "Unknown
format variable
'%t{}' (only one warning)
", c2 )
356 ALIB_DBG( FormatWarningOnce= true; )
363 c2= variable.ConsumeChar();
364 if ( c2 == 'G' ) dest._<NC>( GetName() );
365 else if ( c2 == 'X' ) dest._<NC>( scope.GetLoxName() );
368 ALIB_ASSERT_WARNING( FormatWarningOnce, "ALOX",
369 "Unknown
format variable
'%L{}' (only one warning)
", c2 )
370 ALIB_DBG( FormatWarningOnce= true; )
377 dest._<NC>( ProcessInfo::Current().Name );
382 dest._<NC>( verbosity == Verbosity::Error ? fmt.VerbosityError
383 : verbosity == Verbosity::Warning ? fmt.VerbosityWarning
384 : verbosity == Verbosity::Info ? fmt.VerbosityInfo
385 : fmt.VerbosityVerbose );
390 dest._( Field( domainPath,
392 AutoSizes::Types::Field, domainPath.Length(), 0 ),
393 lang::Alignment::Left ) );
398 dest._<NC>( alib::Dec( CntLogs, GetFormatOther().LogNumberMinDigits ) );
404 // read extra space from format string
406 if( !variable.ConsumeDecDigits( extraSpace ) )
408 integer currentLength= dest.WStringLength();
409 integer tabPos= autoSizes.Main.Next(
410 AutoSizes::Types::Tabstop, currentLength, extraSpace);
411 dest.InsertChars(' ', tabPos - currentLength );
417 dest._<NC>( GetName() );
421 ALIB_ASSERT_WARNING( FormatWarningOnce, "ALOX",
422 "Unknown
format character '{}' (only one warning)
", *( variable.Buffer() -1 ) )
423 ALIB_DBG( FormatWarningOnce= true; )
428void TextLogger::writeTimeDiff( AString& buf, int64_t diffNanos )
430 auto& td= GetFormatTimeDiff();
433 if ( diffNanos < td.Minimum )
435 buf._<NC>( td.None );
439 if ( diffNanos < 1000 )
441 buf._<NC>( alib::Dec( diffNanos, 3 ) )._<NC>( td.Nanos );
445 // we continue with micros
446 int64_t diffMicros= diffNanos / 1000L;
448 // below 1000 microseconds?
449 if ( diffMicros < 1000 )
451 buf._<NC>( alib::Dec( diffMicros, 3 ) );
452 buf._<NC>( td.Micros );
457 if ( diffMicros < 1000000 )
459 buf._<NC>( alib::Dec( (diffMicros / 1000), 3 ) )._<NC>( td.Millis );
464 // below 10 secs (rounded) ?
465 if ( diffMicros < 9995000 )
467 // convert to hundredth of secs
468 int64_t hundredthSecs= ((diffMicros / 1000) + 5) / 10;
470 // print two digits after dot x.xx
471 buf._<NC>( alib::Dec( (hundredthSecs / 100), 1 ) )
473 ._<NC>( alib::Dec( (hundredthSecs % 100), 2 ) )
478 // convert to tenth of secs
479 int64_t tenthSecs= ((diffMicros / 10000) + 5) / 10 ;
482 if ( tenthSecs < 1000 )
484 // print one digits after dot xx.x (round value by adding 5 hundredth)
485 buf._<NC>( alib::Dec( ( tenthSecs / 10 ), 2 ) )
487 ._<NC>( alib::Dec( ( tenthSecs % 10 ), 1 ) )
493 if ( tenthSecs < 6000 )
495 // convert to hundredth of minutes
496 int64_t hundredthMins= tenthSecs / 6;
498 // print two digits after dot x.xx
499 buf._<NC>( alib::Dec( (hundredthMins / 100), 1 ) )
501 ._<NC>( alib::Dec( (hundredthMins % 100), 2 ) )
506 // convert to tenth of minutes
507 int64_t tenthMins= tenthSecs / 60;
510 if ( tenthMins < 1000 )
512 // print one digits after dot xx.x (round value by adding 5 hundredth)
513 buf._<NC>( alib::Dec( (tenthMins / 10), 2 ) )
515 ._<NC>( alib::Dec( (tenthMins % 10), 1 ) )
521 if ( tenthMins < 6000 )
523 // convert to hundredth of hours
524 int64_t hundredthHours= tenthMins / 6;
526 // print two digits after dot x.xx
527 buf._<NC>( alib::Dec( (hundredthHours / 100), 1 ) )
529 ._<NC>( alib::Dec( (hundredthHours % 100), 2 ))
534 // convert to tenth of minutes
535 int64_t tenthHours= tenthMins / 60;
538 if ( tenthHours < 1000 )
540 // print two digits after dot x.xx
541 buf._<NC>( alib::Dec( (tenthHours / 10), 2 ) )
543 ._<NC>( alib::Dec( (tenthHours % 10), 1 ) )
549 if ( tenthHours < 1000 )
551 // print one digits after dot xx.x (round value by adding 5 hundredth)
552 buf._<NC>( alib::Dec( (tenthHours / 10), 2 ) )
554 ._<NC>( alib::Dec( ((tenthHours / 10) % 10), 1 ) )
559 // convert to hundredth of days
560 int64_t hundredthDays= tenthHours * 10 / 24;
563 if ( hundredthDays < 1000 )
565 // print two digits after dot x.xx
566 buf._<NC>( alib::Dec( (hundredthDays / 100), 1 ) )
568 ._<NC>( alib::Dec( (hundredthDays % 100), 2 ) )
573 // 10 days or more (print days plus one digit after the comma)
574 // print one digits after dot xx.x (round value by adding 5 hundredth)
575 buf ._<NC>( alib::Dec( (hundredthDays / 100), 2 ) )
577 ._<NC>( alib::Dec( ((hundredthDays / 10) % 10), 1 ) )
582// #################################################################################################
584// #################################################################################################
585TextLogger::TextLogger( const NString& pName, const NString& typeName, bool pUsesStdStreams )
586: Logger( pName, typeName )
587, usesStdStreams( pUsesStdStreams )
588, varFormatMetaInfo (variables::CampVariable(alib::ALOX))
589, varFormatDateTime (variables::CampVariable(alib::ALOX))
590, varFormatTimeDiff (variables::CampVariable(alib::ALOX))
591, varFormatMultiLine(variables::CampVariable(alib::ALOX))
592, varFormatOther (variables::CampVariable(alib::ALOX))
593, varFormatAutoSizes(variables::CampVariable(alib::ALOX))
594, varReplacements (variables::CampVariable(alib::ALOX))
596 logBuf.SetBuffer( 256 );
597 msgBuf.SetBuffer( 256 );
600TextLogger::~TextLogger()
604 ALIB_ASSERT( msgBuf.IsEmpty(), "ALOX" )
607void TextLogger::AcknowledgeLox( detail::LoxImpl* , lang::ContainerOp op )
609 // --------------- insert ------------------
610 if( op == lang::ContainerOp::Insert )
612 if ( Converter == nullptr )
613 Converter= new textlogger::StandardConverter();
615 // Variable AUTO_SIZES: use last session's values
616 {ALIB_LOCK_WITH(ALOX.GetConfig())
617 varFormatAutoSizes.Declare(Variables::AUTO_SIZES, Name );
618 (void) varFormatAutoSizes.Define();
619 Converter->SetAutoSizes( &varFormatAutoSizes.Get<FormatAutoSizes>().LogMessage );
622 // Variable <name>_FORMAT / <typeName>_FORMAT:
623 {ALIB_LOCK_WITH(ALOX.GetConfig())
624 const Declaration* variableDecl= Declaration::Get( Variables::FORMAT );
625 const Declaration* privateDecl= ALOX.GetConfig()->StoreDeclaration(variableDecl, GetName() );
627 if( !varFormatMetaInfo.Try( privateDecl )
628 && !varFormatMetaInfo.Try( ALOX.GetConfig()->StoreDeclaration(variableDecl, GetTypeName() ) ) )
630 varFormatMetaInfo.Declare( privateDecl );
631 ALIB_ASSERT_ERROR(varFormatMetaInfo.IsDefined(), "ALOX",
632 "Mandatory (usually resourced)
default value is missing
for variable \
"{}\".",
640 auto* privateDecl=
ALOX.GetConfig()->StoreDeclaration(variableDecl, GetName() );
641 if( !varFormatDateTime.Try( privateDecl )
642 && !varFormatDateTime.Try(
ALOX.GetConfig()->StoreDeclaration(variableDecl, GetTypeName() ) ) )
644 varFormatDateTime.Declare( privateDecl );
647 "Mandatory (usually resourced) default value is missing for variable \"{}\".",
655 auto* privateDecl=
ALOX.GetConfig()->StoreDeclaration(variableDecl, GetName() );
656 if( !varFormatTimeDiff.Try( privateDecl )
657 && !varFormatTimeDiff.Try(
ALOX.GetConfig()->StoreDeclaration(variableDecl, GetTypeName() ) ) )
659 varFormatTimeDiff.Declare( privateDecl );
661 "Mandatory (usually resourced) default value is missing for variable \"{}\".",
669 auto* privateDecl=
ALOX.GetConfig()->StoreDeclaration(variableDecl, GetName() );
670 if( !varFormatMultiLine.Try( privateDecl )
671 && !varFormatMultiLine.Try(
ALOX.GetConfig()->StoreDeclaration(variableDecl, GetTypeName() ) ) )
673 varFormatMultiLine.Declare( privateDecl );
675 "Mandatory (usually resourced) default value is missing for variable \"{}\".",
683 auto* privateDecl=
ALOX.GetConfig()->StoreDeclaration(variableDecl, GetName() );
684 if( !varFormatOther.Try( privateDecl )
685 && !varFormatOther.Try(
ALOX.GetConfig()->StoreDeclaration(variableDecl, GetTypeName() ) ) )
687 varFormatOther.Declare( privateDecl );
689 "Mandatory (usually resourced) default value is missing for variable \"{}\".",
697 auto* privateDecl =
ALOX.GetConfig()->StoreDeclaration(variableDecl, GetName() );
698 if( !varReplacements.Try( privateDecl)
699 && !varReplacements.Try(
ALOX.GetConfig()->StoreDeclaration(variableDecl, GetTypeName())) )
701 varReplacements.Declare(privateDecl);
706 if( !varReplacements.IsDefined() )
707 (void) varReplacements.Define(Priority::DefaultValues - 1);
717 for(
auto it= replacements.begin(); it < replacements.end(); it+= 2)
718 if ( it->Equals<
NC>( searched ) )
723 (*it).Reset( replacement );
727 replacements.erase( it );
728 replacements.erase( it );
735 replacements.insert( replacements.end(),
AStringPA(replacements.get_allocator().GetAllocator()) );
736 replacements.back() << searched;
737 replacements.insert( replacements.end(),
AStringPA(replacements.get_allocator().GetAllocator()) );
738 replacements.back() << replacement;
764 for (
size_t i= 0; i < replacements.size() ; i+= 2 )
765 msgBuf.SearchAndReplace( replacements[i],
773 autoSizes.LogMessage.WriteProtected=
true;
777 autoSizes.Main.Restart();
798 if ( multiLine.Mode == 0 )
802 if ( multiLine.Delimiter.IsNotNull() )
803 cntReplacements+=
msgBuf.SearchAndReplace( multiLine.Delimiter, multiLine.DelimiterReplacement, msgBufResetter.
OriginalLength() );
806 String replacement= multiLine.DelimiterReplacement;
813 if ( cntReplacements == 0 )
835 auto prevIndex= autoSizes.Main.ActualIndex;
841 while ( actStart <
msgBuf.Length() )
848 if (multiLine.Delimiter.IsEmpty() )
852 actEnd=
msgBuf.IndexOf<
NC>(
'\n', actStart );
853 if( actEnd > actStart )
855 if(
msgBuf.CharAt<
NC>(actEnd - 1) ==
'\r' )
864 delimLen= multiLine.Delimiter.Length();
865 actEnd=
msgBuf.IndexOf<
NC>( multiLine.Delimiter, actStart );
906 if ( lineNo == 0 && ( multiLine.Mode == 3 || multiLine.Mode == 4 ) )
909 if ( multiLine.Mode == 3 )
912 autoSizes.Main.ActualIndex= prevIndex;
917 lbLenBeforeMsgPart= 0;
921 if ( multiLine.Mode == 2 )
926 autoSizes.Main.ActualIndex= prevIndex;
932 logBuf.ShortenTo( lbLenBeforeMsgPart );
933 autoSizes.Main.ActualIndex= prevIndex;
940 actStart= actEnd + delimLen;
941 if ( actStart >=
msgBuf.Length() )
963 if( autoSizes.Main .IsChanged()
964 || autoSizes.LogMessage.IsChanged() )
SharedConfiguration & GetConfig()
static constexpr character EOMETA[4]
End of meta-information in log string.
ALIB_DLL StandardConverter()
Constructor.
virtual ALIB_DLL void ConvertObjects(AString &target, BoxesMA &logables) override
virtual ALIB_DLL ~StandardConverter() override
Virtual destructor.
std::vector< Formatter * > Formatters
int cntRecursion
A counter to detect recursive calls.
Replacements & GetReplacements()
virtual ALIB_DLL void writeMetaInfo(AString &buffer, detail::Domain &domain, Verbosity verbosity, detail::ScopeInfo &scope)
virtual ALIB_DLL void SetReplacement(const String &searched, const String &replacement)
Variable varFormatMultiLine
virtual ALIB_DLL void Log(detail::Domain &domain, Verbosity verbosity, BoxesMA &logables, detail::ScopeInfo &scope) override
virtual ALIB_DLL void ResetAutoSizes()
AString logBuf
The internal log Buffer.
Variable varFormatMetaInfo
AString msgBuf
The buffers for converting the logables.
virtual void logText(detail::Domain &domain, Verbosity verbosity, AString &msg, detail::ScopeInfo &scope, int lineNumber)=0
Variable varFormatAutoSizes
virtual ALIB_DLL void ClearReplacements()
Removes all pairs of searched strings and their replacement value.
ObjectConverter * Converter
virtual void notifyMultiLineOp(lang::Phase phase)=0
constexpr bool IsNotNull() const
static const Declaration * Get(TEnum element)
#define ALIB_ASSERT_WARNING(cond, domain,...)
#define ALIB_ASSERT_ERROR(cond, domain,...)
#define ALIB_LOCK_WITH(lock)
@ Begin
The start of a transaction.
@ End
The end of a transaction.
This namespaces defines class TextLogger and its helpers.
@ FORMAT_TIME_DIFF
Denotes configuration variable ALOX/LOGGERNAME/FORMAT_TIME_DIFF used by class TextLogger.
@ REPLACEMENTS
Denotes configuration variable ALOX/LOGGERNAME/REPLACEMENTS used by class TextLogger.
@ FORMAT_DATE_TIME
Denotes configuration variable ALOX/LOGGERNAME/FORMAT_DATE_TIME used by class TextLogger.
@ FORMAT_MULTILINE
Denotes configuration variable ALOX/LOGGERNAME/FORMAT_MULTILINE used by class TextLogger.
@ FORMAT_OTHER
Denotes configuration variable ALOX/LOGGERNAME/FORMAT_OTHER used by class TextLogger.
ALIB_DLL Lock STD_IOSTREAMS_LOCK
strings::TStringLengthResetter< character,lang::HeapAllocator > StringLengthResetter
Type alias in namespace alib.
format::FormatterJavaStyle FormatterJavaStyle
Type alias in namespace alib.
variables::Declaration Declaration
Type alias in namespace alib.
format::FormatterPythonStyle FormatterPythonStyle
Type alias in namespace alib.
strings::TAString< character, lang::HeapAllocator > AString
Type alias in namespace alib.
lang::integer integer
Type alias in namespace alib.
lox::ALoxCamp ALOX
The singleton instance of ALib Camp class ALoxCamp.
boxing::TBoxes< MonoAllocator > BoxesMA
Type alias in namespace alib.
strings::TString< character > String
Type alias in namespace alib.
strings::TAString< character, PoolAllocator > AStringPA
Type alias in namespace alib.
characters::character character
Type alias in namespace alib.
AutoSizes Main
The instance used with the meta info format string.