ALib C++ Framework
by
Library Version: 2511 R0
Documentation generated by doxygen
Loading...
Searching...
No Matches
scopeinfo.inl
Go to the documentation of this file.
1//==================================================================================================
2/// \file
3/// This header-file is part of module \alib_alox of the \aliblong.
4///
5/// \emoji :copyright: 2013-2025 A-Worx GmbH, Germany.
6/// Published under #"mainpage_license".
7//==================================================================================================
8ALIB_EXPORT namespace alib { namespace lox { namespace detail {
9
10//==================================================================================================
11/// Encapsulates information of the caller that can be collected. This is platform-specific, in
12/// this case, C++. What we receive from the C++ preprocessor is the source file name
13/// of the calling code, the line number within the source file name and the name of the method
14/// the call is placed in.
15/// Furthermore, we collect the <c>std::type_info*</c> in case the call was not placed in a
16/// static or namespace function.
17///
18/// The method has a list of interface functions that gets such source information and some derived
19/// variants of it. In addition, thread and timer information is stored and managed.
20///
21/// As far as possible, 'lazy' techniques come to practice with this class. This means, only
22/// the things that are queried in-between to invocations of method #"Set" are calculated.
23///
24/// ## Friends ##
25/// class #"Lox"
26//==================================================================================================
28{
29 public:
30#if !ALIB_SINGLE_THREADED
31 /// A map we use to translate thread IDs to thread names
33#endif
34
35 //################################################################################################
36 // Protected fields
37 //################################################################################################
38 protected:
39 #if !DOXYGEN
40 friend struct LoxImpl;
42 friend void LI::GetState( LoxImpl*, NAString&, StateInfo);
43 #endif
44
45 /// Defines how source paths names are to be trimmed. \alox allows a set of global rules and
46 /// a set that is 'local', hence specific to a \b Lox.
48 {
49 NAString Path; ///< The path string
50 NAString TrimReplacement; ///< Optional replacement string for trimmed paths.
51 int TrimOffset; ///< Additional offset of the trim position
52 lang::Inclusion IncludeString; ///< Denotes if #"Path" itself should be included when trimmed
53 lang::Case Sensitivity; ///< The sensitivity of the comparison when trimming
54 variables::Priority Priority; ///< The priority of the rule. Depends on origin: source code, config...)
55 bool IsPrefix; ///< \c true if path was not starting with <c>'*'</c>, when provided.
56 };
57
58 /// List of trim definitions for portions of source paths to be ignored.
59 ALIB_DLL static
60 std::vector<SourcePathTrimRule> GlobalSPTRs;
61
62 /// List of trim definitions for portions of source paths to be ignored.
63 std::vector<SourcePathTrimRule> LocalSPTRs;
64
65 /// Flag to determine if global rules have been read from config already.
66 ALIB_DLL static
68
69 /// If true, next time a source path cannot be trimmed successfully with custom
70 /// trim information provided with
71 /// #"alib::lox::Lox::SetSourcePathTrimRule;Lox::SetSourcePathTrimRule"
72 /// some trim information is automatically created by comparing such source file's path
73 /// with the path of the executable of the current process.
75
76 #if !ALIB_SINGLE_THREADED
77 /// The C++ native ID.
78 std::thread::id threadNativeIDx;
79
80 /// The thread passed with #"Set".
81 Thread* thread =nullptr;
82
83 /// The name of the thread that executed the log.
85
86 /// Dictionary to translate thread IDs into something maybe nicer/shorter.
87 /// The dictionary may be filled by the user of the library using #"Lox.MapThreadName".
89 #endif
90
91 /// Information of a single source file. Stored in field #parsedFileNameCache.
93 {
94 /// Path and name of source file (given by the C++ preprocessor).
96
97 /// Full path of source file (evaluated).
98 NString fullPath =nullptr;
99
100 /// Trimmed path of source file (evaluated).
102
103 /// Prefix for the trimmed path taken from trim rule. Has to be added on writing
104 /// the trimmed path *
106
107 /// File name (evaluated).
108 NString name =nullptr;
109
110 /// File name without extension (evaluated).
112
113 /// Index of last path separator in #origFile.
115
116 /// Constructor.
117 /// @param filename Stored in #origFile.
118 ParsedFileName( const NCString filename) : origFile(filename) {}
119 };
120
121 /// Serves as template parameter \p{TValueDescriptor} of field #parsedFileNameCache.
122 struct ValueDescriptorPFN : containers::TSubsetKeyDescriptor<ParsedFileName, NCString>
123 {
124 /// Provides access to the key-portion of the cached set.
125 /// @param src The cached element.
126 /// @return The key portion of the element.
127 NCString Key (ParsedFileName& src) const { return src.origFile; }
128 };
129
130 /// Least recently used cache of parsed file name.
132
133 /// Holds values for the current scope. Because recursive logging might occur (e.g., when
134 /// parameters rely on method invocations which incorporate log statements), objects of this
135 /// class are stored in stack #callStack.
137 {
138 /// Time of the call that created this record.
140
141 /// The entry from the #parsedFileNameCache
143
144 /// Line number within the source file (given by the C++ preprocessor)
146
147 /// Function/method name (given by the C++ preprocessor)
149
150 /// Type information. Nullptr if call from static or global function.
151 const std::type_info* typeInfo;
152 };
153
154 /// A stack of scopes (allows recursive calls/nested logging).
156
157 /// The current depth of recursive invocations.
159
160 //################################################################################################
161 // Types exposed
162 //################################################################################################
163 public:
164 /// The name of the Lox we are attached to.
166
167
168 //################################################################################################
169 // Constructor
170 //################################################################################################
171 public:
172 /// Constructs a scope info.
173 /// @param name The name of the Lox that this object belongs to.
174 /// Will be converted to upper case.
175 /// @param allocator The monotonic allocator of "our" \b %Lox, used for long-term allocations
177 ScopeInfo( const NString& name, MonoAllocator& allocator);
178
179 //#################################################################################################
180 // public interface
181 //#################################################################################################
182 public:
183 /// Changes the capacity of the \b %LRUCacheTable for parsed file names by calling
184 /// #"LRUCacheTable::Reserve;*".
185 /// @param numberOfLists The number of LRU-lists to use.
186 /// @param entriesPerList The maximum length of each cache list.
187 void SetFileNameCacheCapacity( integer numberOfLists, integer entriesPerList )
188 { parsedFileNameCache.Reserve( numberOfLists, entriesPerList ); }
189
190 /// Stores C++ specific caller parameters and some other values like the time stamp.
191 /// Also, flags thread information as not received, yet.
192 /// Counts the recursion counter up.
193 /// @param ci The caller information.
195 void Set( const lang::CallerInfo& ci );
196
197 /// Releases latest scope information.
199
200
201 /// Implements for #"Lox::SetSourcePathTrimRule;2" and #"Lox::ClearSourcePathTrimRules;2".
202 /// @param path The path to search for. If not starting with <c> '*'</c>,
203 /// a prefix is searched.
204 /// @param includeString Determines if \p{path} should be included in the trimmed path or not.
205 /// @param trimOffset Adjusts the portion of \p{path} that is trimmed. 999999 to clear!
206 /// @param sensitivity Determines if the comparison of \p{path} with a source file's path
207 /// is performed case-sensitive or not.
208 /// @param trimReplacement Replacement string for trimmed portion of the path.
209 /// @param reach Denotes whether the rule is applied locally (to this \b %Lox only)
210 /// or applies to all instances of class \b %Lox.
211 /// Defaults to \b %Reach::Global.
212 /// @param priority The priority of the setting.
214 void SetSourcePathTrimRule( const NCString& path,
215 lang::Inclusion includeString,
216 int trimOffset,
217 lang::Case sensitivity,
218 const NString& trimReplacement,
219 lang::Reach reach,
220 Priority priority );
221
222 /// Receives the name of the \b Lox we are belonging to (this is a 1:1 relationship).
223 /// @return The name of the \b Lox.
224 const NString GetLoxName() { return loxName; }
225
226 /// Receives the original filename and path of the source file
227 /// (usually provided by the preprocessor).
228 /// @return The full path and filename of the source file.
229 const NCString& GetOrigFile() { return callStack[size_t(callStackSize)].Parsed->origFile; }
230
231 /// Receives the path of the source file (not trimmed, see #GetTrimmedPath).
232 /// @return The path of the source file.
234 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
235 if( srcFile.fullPath.IsNull() ) {
236 integer idx= getPathLength();
237 if( idx >= 0 )
238 srcFile.fullPath= NString( srcFile.origFile.Buffer(), idx );
239 else
240 srcFile.fullPath= "";
241 }
242
243 return srcFile.fullPath;
244 }
245
246 /// Writes the path of the source file, trimmed according to trim-information provided
247 /// with #SetSourcePathTrimRule or detected according to #AutoDetectTrimableSourcePath.
248 /// @param target The target string to append the trimmed path to.
249 void GetTrimmedPath( AString& target ) {
250 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
251 if( srcFile.trimmedPath.IsNull() )
252 trimPath();
253
254 target._( srcFile.trimmedPathPrefix )
255 ._( srcFile.trimmedPath );
256 }
257
258 /// Receives the source file name excluding the path (usually provided by the preprocessor).
259 /// @return The source file name excluding the path
261 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
262 if( srcFile.name.IsNull() ) {
263 integer idx= getPathLength();
264 if( idx >= 0 )
265 srcFile.name= NString( srcFile.origFile.Buffer() + idx + 1,
266 srcFile.origFile.Length() - idx - 1 );
267 else
268 srcFile.name= "";
269 }
270 return srcFile.name;
271 }
272
273 /// Receives the source file name excluding the path and without an extension
274 /// (usually provided by the preprocessor).
275 /// @return The source file name excluding the path and extension.
277 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
278 if( srcFile.nameWOExt.IsNull() ) {
279 srcFile.nameWOExt= GetFileName();
280 integer lastDot= srcFile.nameWOExt.LastIndexOf( '.' );
281 if ( lastDot > 0 )
282 srcFile.nameWOExt= NString( srcFile.nameWOExt.Buffer(), lastDot );
283 }
284 return srcFile.nameWOExt;
285 }
286
287
288 /// Receives the method name (usually provided by the preprocessor).
289 /// @return The method name.
290 const NCString GetMethod() { return callStack[size_t(callStackSize)].origMethod; }
291
292 /// Receives the source file line number (usually provided by the preprocessor).
293 /// @return The source file line number.
294 int GetLineNumber() { return callStack[size_t(callStackSize)].origLine; }
295
296 /// The timestamp of the last invocation of #Set.
297 /// @return The latest timestamp.
298 Ticks GetTimeStamp() { return callStack[size_t(callStackSize)].timeStamp; }
299
300 /// Receives the type information of the caller.
301 /// If called from global function or static method, this will be \c nullptr.
302 /// @returns The type information, if available.
303 const std::type_info* GetTypeInfo() { return callStack[size_t(callStackSize)].typeInfo; }
304
305#if !ALIB_SINGLE_THREADED
306 /// Receives the thread ID of the caller.
307 /// @returns The thread ID.
309 if( thread == nullptr )
311 return thread->GetID();
312 }
313
314 /// Receives the thread ID of the caller.
315 /// @returns The thread ID.
316 std::thread::id GetThreadNativeID() { return threadNativeIDx; }
317
318 /// Receives information about the thread that the current call was invoked with.
319 /// @param id Output parameter receiving the \alib thread ID. If nullptr, it will be
320 /// ignored.
321 /// @returns The name of the current thread. The id is stored within the provided
322 /// pointer.
324 if ( threadName.IsNull() ) {
325 // get current thread, if not passed with set()
326 if( thread == nullptr )
328
329 if (id != nullptr)
330 *id= thread->GetID();
331
332 // do we have a dictionary entry?
333 auto it= threadDictionary.Find( thread->GetID() );
334 if (it != threadDictionary.end() )
335 threadName= it->second;
336 else
337 threadName= thread->GetName();
338 }
339
340 return threadName;
341 }
342#endif
343
344 //################################################################################################
345 // Internals
346 //################################################################################################
347 protected:
348
349 /// Tries to trim the source file's path. Sets variable SourceFile::trimmedPath to either
350 /// the successfully trimmed path or to the non-trimmed one. This way, it is executed
351 /// only once, at it is 'lazily' invoked by #GetTrimmedPath()
353 void trimPath();
354
355 /// Gets position of path/filename separator. This is evaluated only once after an
356 /// invocation of #Set.
357 /// @return The index of the path separator in SourceFile::origFile.
359 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
360 if( srcFile.origFilePathLength == -2 )
361 srcFile.origFilePathLength= srcFile.origFile.LastIndexOf( system::DIRECTORY_SEPARATOR );
362 return srcFile.origFilePathLength;
363 }
364}; // class ScopeInfo
365
366}}} // namespace [alib::lox::detail]
#define ALIB_DLL
Definition alib.inl:573
#define ALIB_ASSERT(cond, domain)
Definition alib.inl:1143
#define ALIB_EXPORT
Definition alib.inl:562
static std::vector< SourcePathTrimRule > GlobalSPTRs
List of trim definitions for portions of source paths to be ignored.
Definition scopeinfo.inl:60
const NString GetFileNameWithoutExtension()
const NCString & GetOrigFile()
const alib::String & GetThreadNameAndID(threads::ThreadID *id)
std::thread::id GetThreadNativeID()
StdVectorMA< FrameRecord > callStack
A stack of scopes (allows recursive calls/nested logging).
void GetTrimmedPath(AString &target)
threads::ThreadID GetThreadID()
static bool GlobalSPTRsReadFromConfig
Flag to determine if global rules have been read from config already.
Definition scopeinfo.inl:67
ScopeInfo(const NString &name, MonoAllocator &allocator)
Definition scopeinfo.cpp:63
void SetSourcePathTrimRule(const NCString &path, lang::Inclusion includeString, int trimOffset, lang::Case sensitivity, const NString &trimReplacement, lang::Reach reach, Priority priority)
NString loxName
The name of the Lox we are attached to.
void SetFileNameCacheCapacity(integer numberOfLists, integer entriesPerList)
ThreadDictionary threadDictionary
Definition scopeinfo.inl:88
void PopNestedScope()
Releases latest scope information.
HashMap< MonoAllocator, threads::ThreadID, String32 > ThreadDictionary
A map we use to translate thread IDs to thread names.
Definition scopeinfo.inl:32
String threadName
The name of the thread that executed the log.
Definition scopeinfo.inl:84
LRUCacheTable< MonoAllocator, ValueDescriptorPFN, std::hash< NString > > parsedFileNameCache
Least recently used cache of parsed file name.
Thread * thread
The thread passed with #"Set".
Definition scopeinfo.inl:81
int callStackSize
The current depth of recursive invocations.
void Set(const lang::CallerInfo &ci)
std::vector< SourcePathTrimRule > LocalSPTRs
List of trim definitions for portions of source paths to be ignored.
Definition scopeinfo.inl:63
std::thread::id threadNativeIDx
The C++ native ID.
Definition scopeinfo.inl:78
const std::type_info * GetTypeInfo()
TAString & _(const TAppendable &src)
static Thread * Get(std::thread::id nativeID)
Definition thread.cpp:314
Reach
Denotes the reach of something.
Case
Denotes upper and lower case character treatment.
Inclusion
Denotes how members of a set something should be taken into account.
constexpr PathCharType DIRECTORY_SEPARATOR
The standard path separator character. Defaults to '\' on Windows OS, '/' else.
Definition path.inl:63
integer ThreadID
The ALib thread identifier type.
Definition thread.inl:23
monomem::TMonoAllocator< lang::HeapAllocator > MonoAllocator
strings::TString< nchar > NString
Type alias in namespace alib.
Definition string.inl:2181
containers::LRUCacheTable< TAllocator, TValueDescriptor, THash, TEqual > LRUCacheTable
Type alias in namespace alib.
threads::Thread Thread
Type alias in namespace alib.
Definition thread.inl:387
strings::TCString< nchar > NCString
Type alias in namespace alib.
Definition cstring.inl:408
alib::variables::Priority Priority
Type alias in namespace alib.
strings::TAString< nchar, lang::HeapAllocator > NAString
Type alias in namespace alib.
lang::integer integer
Type alias in namespace alib.
Definition integers.inl:149
containers::HashMap< TAllocator, TKey, TMapped, THash, TEqual, THashCaching, TRecycling > HashMap
Type alias in namespace alib.
strings::TString< character > String
Type alias in namespace alib.
Definition string.inl:2172
time::Ticks Ticks
Type alias in namespace alib.
Definition ticks.inl:79
strings::TAString< character, lang::HeapAllocator > AString
Type alias in namespace alib.
std::vector< T, StdMA< T > > StdVectorMA
Type alias in namespace alib.
static void GetState(LoxImpl *impl, NAString &buf, StateInfo flags)
static void MapThreadName(LoxImpl *impl, const String &threadName, threads::ThreadID id)
Ticks timeStamp
Time of the call that created this record.
const std::type_info * typeInfo
Type information. Nullptr if call from static or global function.
NCString origMethod
Function/method name (given by the C++ preprocessor).
ParsedFileName * Parsed
The entry from the parsedFileNameCache.
int origLine
Line number within the source file (given by the C++ preprocessor).
Information of a single source file. Stored in field parsedFileNameCache.
Definition scopeinfo.inl:93
NCString origFile
Path and name of source file (given by the C++ preprocessor).
Definition scopeinfo.inl:95
NString name
File name (evaluated).
NString nameWOExt
File name without extension (evaluated).
integer origFilePathLength
Index of last path separator in origFile.
NString fullPath
Full path of source file (evaluated).
Definition scopeinfo.inl:98
NString trimmedPath
Trimmed path of source file (evaluated).
int TrimOffset
Additional offset of the trim position.
Definition scopeinfo.inl:51
lang::Inclusion IncludeString
Denotes if #"Path" itself should be included when trimmed.
Definition scopeinfo.inl:52
variables::Priority Priority
The priority of the rule. Depends on origin: source code, config...).
Definition scopeinfo.inl:54
bool IsPrefix
true if path was not starting with '*', when provided.
Definition scopeinfo.inl:55
lang::Case Sensitivity
The sensitivity of the comparison when trimming.
Definition scopeinfo.inl:53
NAString TrimReplacement
Optional replacement string for trimmed paths.
Definition scopeinfo.inl:50
Serves as template parameter TValueDescriptor of field parsedFileNameCache.
NCString Key(ParsedFileName &src) const