ALib C++ Library
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 \ref mainpage_license "Boost Software 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 \alib{lox;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;
41 friend void LI::MapThreadName(LoxImpl*, const String&, threads::ThreadID);
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 /// \ref 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 \alox{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 /// \alib{containers;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 /// Does the job for
202 /// \ref alib::lox::Lox::SetSourcePathTrimRule "Lox::SetSourcePathTrimRule" and
203 /// \ref alib::lox::Lox::ClearSourcePathTrimRules "Lox::ClearSourcePathTrimRules".
204 ///
205 /// @param path The path to search for. If not starting with <c> '*'</c>,
206 /// a prefix is searched.
207 /// @param includeString Determines if \p{path} should be included in the trimmed path or not.
208 /// @param trimOffset Adjusts the portion of \p{path} that is trimmed. 999999 to clear!
209 /// @param sensitivity Determines if the comparison of \p{path} with a source file's path
210 /// is performed case-sensitive or not.
211 /// @param trimReplacement Replacement string for trimmed portion of the path.
212 /// @param reach Denotes whether the rule is applied locally (to this \b %Lox only)
213 /// or applies to all instances of class \b %Lox.
214 /// Defaults to \b %Reach::Global.
215 /// @param priority The priority of the setting.
217 void SetSourcePathTrimRule( const NCString& path,
218 lang::Inclusion includeString,
219 int trimOffset,
220 lang::Case sensitivity,
221 const NString& trimReplacement,
222 lang::Reach reach,
223 Priority priority );
224
225 /// Receives the name of the \b Lox we are belonging to (this is a 1:1 relationship).
226 /// @return The name of the \b Lox.
227 const NString GetLoxName() { return loxName; }
228
229 /// Receives the original filename and path of the source file
230 /// (usually provided by the preprocessor).
231 /// @return The full path and filename of the source file.
232 const NCString& GetOrigFile() { return callStack[size_t(callStackSize)].Parsed->origFile; }
233
234 /// Receives the path of the source file (not trimmed, see #GetTrimmedPath).
235 /// @return The path of the source file.
237 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
238 if( srcFile.fullPath.IsNull() ) {
239 integer idx= getPathLength();
240 if( idx >= 0 )
241 srcFile.fullPath= NString( srcFile.origFile.Buffer(), idx );
242 else
243 srcFile.fullPath= "";
244 }
245
246 return srcFile.fullPath;
247 }
248
249 /// Writes the path of the source file, trimmed according to trim-information provided
250 /// with #SetSourcePathTrimRule or detected according to #AutoDetectTrimableSourcePath.
251 /// @param target The target string to append the trimmed path to.
252 void GetTrimmedPath( AString& target ) {
253 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
254 if( srcFile.trimmedPath.IsNull() )
255 trimPath();
256
257 target._( srcFile.trimmedPathPrefix )
258 ._( srcFile.trimmedPath );
259 }
260
261 /// Receives the source file name excluding the path (usually provided by the preprocessor).
262 /// @return The source file name excluding the path
264 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
265 if( srcFile.name.IsNull() ) {
266 integer idx= getPathLength();
267 if( idx >= 0 )
268 srcFile.name= NString( srcFile.origFile.Buffer() + idx + 1,
269 srcFile.origFile.Length() - idx - 1 );
270 else
271 srcFile.name= "";
272 }
273 return srcFile.name;
274 }
275
276 /// Receives the source file name excluding the path and without an extension
277 /// (usually provided by the preprocessor).
278 /// @return The source file name excluding the path and extension.
280 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
281 if( srcFile.nameWOExt.IsNull() ) {
282 srcFile.nameWOExt= GetFileName();
283 integer lastDot= srcFile.nameWOExt.LastIndexOf( '.' );
284 if ( lastDot > 0 )
285 srcFile.nameWOExt= NString( srcFile.nameWOExt.Buffer(), lastDot );
286 }
287 return srcFile.nameWOExt;
288 }
289
290
291 /// Receives the method name (usually provided by the preprocessor).
292 /// @return The method name.
293 const NCString GetMethod() { return callStack[size_t(callStackSize)].origMethod; }
294
295 /// Receives the source file line number (usually provided by the preprocessor).
296 /// @return The source file line number.
297 int GetLineNumber() { return callStack[size_t(callStackSize)].origLine; }
298
299 /// The timestamp of the last invocation of #Set.
300 /// @return The latest timestamp.
301 Ticks GetTimeStamp() { return callStack[size_t(callStackSize)].timeStamp; }
302
303 /// Receives the type information of the caller.
304 /// If called from global function or static method, this will be \c nullptr.
305 /// @returns The type information, if available.
306 const std::type_info* GetTypeInfo() { return callStack[size_t(callStackSize)].typeInfo; }
307
308#if !ALIB_SINGLE_THREADED
309 /// Receives the thread ID of the caller.
310 /// @returns The thread ID.
312 if( thread == nullptr )
314 return thread->GetID();
315 }
316
317 /// Receives the thread ID of the caller.
318 /// @returns The thread ID.
319 std::thread::id GetThreadNativeID() { return threadNativeIDx; }
320
321 /// Receives information about the thread that the current call was invoked with.
322 /// @param id Output parameter receiving the \alib thread ID. If nullptr, it will be
323 /// ignored.
324 /// @returns The name of the current thread. The id is stored within the provided
325 /// pointer.
327 if ( threadName.IsNull() ) {
328 // get current thread, if not passed with set()
329 if( thread == nullptr )
331
332 if (id != nullptr)
333 *id= thread->GetID();
334
335 // do we have a dictionary entry?
336 auto it= threadDictionary.Find( thread->GetID() );
337 if (it != threadDictionary.end() )
338 threadName= it->second;
339 else
340 threadName= thread->GetName();
341 }
342
343 return threadName;
344 }
345#endif
346
347 //################################################################################################
348 // Internals
349 //################################################################################################
350 protected:
351
352 /// Tries to trim the source file's path. Sets variable SourceFile::trimmedPath to either
353 /// the successfully trimmed path or to the non-trimmed one. This way, it is executed
354 /// only once, at it is 'lazily' invoked by #GetTrimmedPath()
356 void trimPath();
357
358 /// Gets position of path/filename separator. This is evaluated only once after an
359 /// invocation of #Set.
360 /// @return The index of the path separator in SourceFile::origFile.
362 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
363 if( srcFile.origFilePathLength == -2 )
364 srcFile.origFilePathLength= srcFile.origFile.LastIndexOf( system::DIRECTORY_SEPARATOR );
365 return srcFile.origFilePathLength;
366 }
367}; // class ScopeInfo
368
369}}} // namespace [alib::lox::detail]
static ALIB_DLL 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 ALIB_DLL bool GlobalSPTRsReadFromConfig
Flag to determine if global rules have been read from config already.
Definition scopeinfo.inl:67
ALIB_DLL ScopeInfo(const NString &name, MonoAllocator &allocator)
Definition scopeinfo.cpp:63
HashMap< MonoAllocator, threads::ThreadID, String32 > ThreadDictionary
A map we use to translate thread IDs to thread names.
Definition scopeinfo.inl:32
ALIB_DLL 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.
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.
ALIB_DLL 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 ALIB_DLL Thread * Get(std::thread::id nativeID)
Definition thread.cpp:314
#define ALIB_DLL
Definition alib.inl:503
#define ALIB_ASSERT(cond, domain)
Definition alib.inl:1065
#define ALIB_EXPORT
Definition alib.inl:497
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
containers::LRUCacheTable< TAllocator, TValueDescriptor, THash, TEqual > LRUCacheTable
Type alias in namespace alib.
strings::TAString< character, lang::HeapAllocator > AString
Type alias in namespace alib.
std::vector< T, StdMA< T > > StdVectorMA
Type alias in namespace alib.
lang::integer integer
Type alias in namespace alib.
Definition integers.inl:149
strings::TString< nchar > NString
Type alias in namespace alib.
Definition string.inl:2198
strings::TAString< nchar, lang::HeapAllocator > NAString
Type alias in namespace alib.
containers::HashMap< TAllocator, TKey, TMapped, THash, TEqual, THashCaching, TRecycling > HashMap
Type alias in namespace alib.
monomem::TMonoAllocator< lang::HeapAllocator > MonoAllocator
threads::Thread Thread
Type alias in namespace alib.
Definition thread.inl:387
strings::TCString< nchar > NCString
Type alias in namespace alib.
Definition cstring.inl:484
alib::variables::Priority Priority
Type alias in namespace alib.
strings::TString< character > String
Type alias in namespace alib.
Definition string.inl:2189
time::Ticks Ticks
Type alias in namespace alib.
Definition ticks.inl:79
static ALIB_DLL void MapThreadName(LoxImpl *impl, const String &threadName, threads::ThreadID id)
static ALIB_DLL void GetState(LoxImpl *impl, NAString &buf, StateInfo flags)
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