Stroika Library 3.0d25
 
Loading...
Searching...
No Matches
Trace.h
Go to the documentation of this file.
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2026. All rights reserved
3 */
4#ifndef _Stroika_Foundation_Debug_Trace_h_
5#define _Stroika_Foundation_Debug_Trace_h_ 1
6
7#include "Stroika/Foundation/StroikaPreComp.h"
8
9#include <array>
10#include <filesystem>
11#include <span>
12#include <thread>
13
14#include "Stroika/Foundation/Common/Common.h"
17
18/**
19 * \file
20 *
21 * \note Code-Status: <a href="Code-Status.md#Beta">Beta</a>
22 *
23 */
24
26 template <typename CHAR_T>
27 struct FormatString;
28 namespace Private_ {
29 template <typename RESULT, typename F, typename... ARGS>
30 RESULT WithFormatArgs_ (F&& f, const ARGS&... args); // @see Characters/Format.h
31 }
32}
33
34namespace Stroika::Foundation::Debug {
35
36 /**
37 * If qStroika_Foundation_Debug_TraceToFile is set true, then DbgTrace () and other Trace calls all go both to the usual debugger output
38 * screen, and to an auto-generated logfile.
39 *
40 * This can be handy for building a version of code to hand to customers with an irreproducible bug to get a detailed
41 * report of what happened. Its also handy for embedded or timing sensative programs where capturing the log
42 * of exactly what happened is helpful.
43 */
44#if !defined(qStroika_Foundation_Debug_TraceToFile)
45#if defined(qTraceToFile)
46#warning "use qStroika_Foundation_Debug_TraceToFile since Stroika v3.0d4 "
47#define qStroika_Foundation_Debug_TraceToFile qTraceToFile // (and leave qTraceToFile alone: redefining it would change this too)
48#else
49#define qStroika_Foundation_Debug_TraceToFile 0
50#endif
51#endif
52
53 /*
54 * qStroika_Foundation_Debug_DefaultTracingOn provides the default configuration for whether or not DbgTrace logs
55 * or just is 'compiled out' of target programs.
56 *
57 * Note ALSO - many Stroika modules (CPP files) contain a private
58 * // Comment this in to turn on tracing in this module
59 * //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
60 * define.
61 *
62 * This is often not enabled by default because it could produce lots of uninteresting noise in logfiles
63 * (when tracing on).
64 *
65 * Turn per-module USE_NOISY_TRACE_IN_THIS_MODULE_ flags on selectively just to enable extra detailed logging on a per module basis.
66 */
67#if !defined(qStroika_Foundation_Debug_DefaultTracingOn)
68
69#if defined(qDefaultTracingOn)
70#warning "use qStroika_Foundation_Debug_DefaultTracingOn since Stroika v3.0d4 "
71#define qStroika_Foundation_Debug_DefaultTracingOn qDefaultTracingOn
72#else
73#define qStroika_Foundation_Debug_DefaultTracingOn qStroika_Foundation_Debug_AssertionsChecked
74#endif
75#endif
76
77 /**
78 * \brief if true, emit a much shorter thread ID, making - I suspect (testing) for terser and clearer tracelogs.
79 * Only downside is that you must find first occurrence of that index to find real threadId, and use that in waits, etc.
80 *
81 * This is defined as a #define, so you can turn it off when building Stroika. I'm unsure if the showing of thread indexes
82 * helps readability of the tracelog, but I think it does.
83 *
84 * This is somewhat helpful on windows, but much more so on 64-bit linux with very long fairly random looking thread ids.
85 */
86#ifndef qStroika_Foundation_Debug_ShowThreadIndex
87#define qStroika_Foundation_Debug_ShowThreadIndex 1
88#endif
89
90 namespace Private_ {
91 // The 'TraceLastBufferedWriteTokenType' overload of EmitTraceMessage allows you to specify a set of (trailing) characters to
92 // be temporarily buffered. These characters are not immediately emitted, and can be cleared via UnputBufferedCharactersForMatchingToken ().
93 // They will eventually be flushed out on the next call to EmitTraceMessage ().
94 using TraceLastBufferedWriteTokenType = int;
95 class Emitter;
96
97 // Characters::IFormatLiteral ("..."_f), which this header cannot include
98 template <typename T>
99 concept IFormatLiteral_ = requires { typename remove_cvref_t<T>::FormatLiteralTag_; };
100 }
101
102 /**
103 * Just for debugging purposes, get the name displayed in the trace log for the given thread-id.
104 */
105 wstring GetDbgTraceThreadName (thread::id threadID);
106 string GetDbgTraceThreadName_A (thread::id threadID);
107
108#if qStroika_Foundation_Debug_TraceToFile
109 /**
110 * @brief Return the path where the tracefile exists. Note this is only available if the qStroika_Foundation_Debug_TraceToFile function is enabled.
111 */
112 filesystem::path GetTraceFileName ();
113#endif
114
115 /**
116 * Define a new start/end context (with optional label) for trace messages emitted with DbgTrace (), and indent future
117 * DbgTrace () messages (from this thread) during the lifetime of TraceContextBumper.
118 *
119 * \par Example Usage
120 * \code
121 * Debug::TraceContextBumper ctx{"MyXercesMemMgr_::DUMPCurMemStats"};
122 * DbgTrace (L"x");
123 * \endcode
124 *
125 * Generates log output:
126 * <MyXercesMemMgr_::DUMPCurMemStats>
127 * x
128 * </MyXercesMemMgr_::DUMPCurMemStats>
129 *
130 * \par Example Usage
131 * \code
132 * Debug::TraceContextBumper ctx{"OptionsFile::ReadRaw", "readfilename={}"_f, GetReadFilePath_ ()};
133 * \endcode
134 *
135 * Generates log output (assuming ReadRaw is quick and doesn't do more DbgTrace calls):
136 * <OptionsFile::ReadRaw (readfilename=C:\Users\Lewis\AppData\Local\Temp\MyModule.json)/>
137 *
138 * \par Example Usage
139 * \code
140 * Debug::TraceContextBumper ctx { Stroika_Foundation_Debug_OptionalizeTraceArgs ("OptionsFile::ReadRaw", "readfilename={}"_f, GetReadFilePath_ ().c_str ()) };
141 * DbgTrace (L"x");
142 * \endcode
143 *
144 * Generates log output:
145 * <OptionsFile::ReadRaw (readfilename=C:\Users\Lewis\AppData\Local\Temp\MyModule.json)>
146 * x
147 * </OptionsFile::ReadRaw>
148 *
149 * \par Example Usage
150 * \code
151 * struct X {
152 * // ... lots of data members - and you get a crash between constructor or destruction of some of them
153 * // ... use this trick to see dbgmessages BETWEEN construction and destruction of each member
154 * ComplexObject fComplexObject1;
155 * TraceContextBumper tmpNoteAfterComplexObj1 {"after fComplexObject1"};
156 * ComplexObject fComplexObject2;
157 * TraceContextBumper tmpNoteAfterComplexObj2 {"after fComplexObject2"};
158 * };
159 * \endcode
160 *
161 * \note ***Not Cancelation Point*** - and uses noexcept
162 * \note safe to call and does nothing if !qStroika_Foundation_Debug_DefaultTracingOn
163 */
164 class TraceContextBumper final {
165 public:
166 /**
167 *
168 * @todo REDO ALL THESE DOCS --- AS OF 2024-03-22
169 *
170 * If constructor taking const char* used, the argument must be ASCII characters.
171 *
172 * The constructor with 'extraFmt', emits the extra data in the heading of the trace message, but
173 * not the close brace. This can allow for more terse TraceContextBumper messages, and more terse
174 * calling usage.
175 *
176 * For TraceContextBumper (const wchar_t* contextName, const wchar_t* extraFmt, ...) usage, @see Stroika_Foundation_Debug_OptionalizeTraceArgs
177 * to optionally suppress side-effects.
178 *
179 * \note ***Not Cancelation Point*** - and uses noexcept
180 */
181 TraceContextBumper () noexcept;
182 template <typename CHAR_T>
183 TraceContextBumper (const CHAR_T* contextName) noexcept
184 requires (same_as<CHAR_T, char> or same_as<CHAR_T, wchar_t>);
185 template <typename CHAR_T, typename FCHAR_T, typename... ARGS>
186 TraceContextBumper (const CHAR_T* contextName, Characters::FormatString<FCHAR_T> fmt, ARGS&&... args) noexcept
187 requires ((same_as<CHAR_T, char> or same_as<CHAR_T, wchar_t>) and (same_as<FCHAR_T, char> or same_as<FCHAR_T, wchar_t>));
188 template <typename CHAR_T, Private_::IFormatLiteral_ FORMAT_LITERAL, typename... ARGS>
189 TraceContextBumper (const CHAR_T* contextName, const FORMAT_LITERAL& fmt, ARGS&&... args) noexcept
190 requires (same_as<CHAR_T, char> or same_as<CHAR_T, wchar_t>); ///< \brief fmt "..."_f: args checked at compile time
191 TraceContextBumper (const TraceContextBumper&) = delete;
192
193 public:
194 // legacy API
195 [[deprecated ("Since Stroika v3.0d6 - use _f format strings")]] TraceContextBumper (const wchar_t* contextName,
196 const wchar_t* extraFmt, ...) noexcept;
197
198#if qStroika_Foundation_Debug_DefaultTracingOn
199 private:
200 // Nothing too important about this constant, but not so long as to be hard to read
201 static constexpr size_t kMaxContextNameLen_{80};
202
203 using CHAR_ARRAY_T = array<wchar_t, kMaxContextNameLen_ + 1>; // enforce always nul-terminated strings - but can copy by value
204
205 private:
206 // spans are outer bounds of strings - also look for NUL-term to find string length - require they are nul-terminated (so not sure why span is useful - @todo rethink)
207 TraceContextBumper (CHAR_ARRAY_T mainName, CHAR_ARRAY_T extraTextAtTop = {}) noexcept;
208#endif
209
210 public:
211#if qStroika_Foundation_Debug_DefaultTracingOn
212 ~TraceContextBumper () noexcept;
213#else
214 ~TraceContextBumper () noexcept = default;
215#endif
216
217 public:
218 nonvirtual TraceContextBumper& operator= (const TraceContextBumper&) = delete;
219
220#if qStroika_Foundation_Debug_DefaultTracingOn
221 public:
222 bool fDoEndMarker{false};
223
224 public:
225 static unsigned int GetCount ();
226
227 private:
228 CHAR_ARRAY_T fSavedContextName_{};
229 Private_::TraceLastBufferedWriteTokenType fLastWriteToken_{}; // used to COMBINE items into a single line if they happen quickly enuf
230
231 private:
232 template <typename CHAR_T>
233 static CHAR_ARRAY_T cvt2WChartArrayTrunc_ (span<const CHAR_T> contextName);
234 template <typename CHAR_T>
235 static CHAR_ARRAY_T cvt2WChartArrayTrunc_ (const CHAR_T* contextName);
236 template <typename CHAR_T, typename... ARGS>
237 CHAR_ARRAY_T ProcessFmtString_ (Characters::FormatString<CHAR_T> fmt, ARGS&&... args) noexcept
238 requires (same_as<CHAR_T, char> or same_as<CHAR_T, wchar_t>);
239
240 private:
241 static void IncCount_ () noexcept;
242 static void DecrCount_ () noexcept;
243#endif
244 };
245
246 /**
247 * Suppress trace messages (in this thread) for the lifetime of this object.
248 *
249 * \par Example Usage
250 * \code
251 * {
252 * Debug::TraceContextSuppressor suppressTraceInThisBlock;
253 * DbgTrace (L"x"); // suppressed
254 * }
255 * DbgTrace (L"x"); // emitted
256 * \endcode
257 */
259 public:
260 /**
261 */
262 TraceContextSuppressor () noexcept;
264 TraceContextSuppressor& operator= (const TraceContextSuppressor&) = delete;
265
266 public:
268
269 public:
270 static bool GetSuppressTraceInThisThread ();
271
272 private:
273 static inline thread_local unsigned int tSuppressCnt_;
274 };
275
276 /**
277 * \def Stroika_Foundation_Debug_OptionalizeTraceArgs
278 *
279 * This is meant to be used with the 2+ argument Debug::TraceContextBumper constructor (_f format string), to optionally suppress side-effects
280 * of trace arguments when tracing is disabled (at compile time).
281 *
282 * \note this may still be useful in Stroika v3 and later, but was mostly useful in before, switching to use of variadic templates, since now
283 * the compiler can see the variadic and format parameters are unused for anything, so probably is able to optimize them away.
284 */
285#if qStroika_Foundation_Debug_DefaultTracingOn
286#define Stroika_Foundation_Debug_OptionalizeTraceArgs(...) __VA_ARGS__
287#else
288#define Stroika_Foundation_Debug_OptionalizeTraceArgs(...)
289#endif
290
291 /**
292 * \def DbgTrace
293 *
294 * This function either does NOTHING (trying to not even evaluate its arguments)
295 * or does a printf style PRINT function by delegating to @'EmitTraceMessage'. Which of
296 * these two behaviors you see is conditioned on @'qStroika_Foundation_Debug_DefaultTracingOn'</p>
297 *
298 * \note ***Not Cancelation Point*** - and uses noexcept
299 * So you can call this freely without worrying about Throw (ThreadAbortException) etc
300 * (though beware of passing arguments to DbgTrace() which may be cancelation points)
301 *
302 * \note - DbgTrace can take either printf style format strings, or _f format strings.
303 *
304 * \par Example Usage
305 * \code
306 * auto url = IO::Network::URI{"http://www.sophists.com"};
307 * DbgTrace ("u = {}"_f, url); // output "u = 'http://www.sophists.com'"
308 * \endcode
309 *
310 * @todo - redo NOT as MACRO but as FUNCTION call (to emittracemessage)
311 *
312 * template <typename CHAR_T, typename... Args>
313 nonvirtual void DbgTrace (Characters::FormatString<CHAR_T> fmt, Args&&... args) noexcept
314 {
315 or some such
316 try {
317 Stroika::Foundation::Debug::Private_::Emitter::Get ().EmitTraceMessage (fmt.get (), Common::StdCompat::make_wformat_args (args...));
318 }
319 catch (...) {
320 }
321 }
322 but only after 'd' stage development so I can lose C-style FMT string overloads...
323 */
324#if qStroika_Foundation_Debug_DefaultTracingOn
325#define DbgTrace Stroika::Foundation::Debug::Private_::Emitter::Get ().EmitTraceMessage
326#else
327#define DbgTrace _NoOp_
328#endif
329
330}
331
332/*
333 ********************************************************************************
334 ***************************** Implementation Details ***************************
335 ********************************************************************************
336 */
337#include "Trace.inl"
338
339#endif /*_Stroika_Foundation_Debug_Trace_h_*/
RESULT WithFormatArgs_(F &&f, const ARGS &... args)
wstring GetDbgTraceThreadName(thread::id threadID)
Definition Trace.cpp:542
Stroika's format string: it always formats WIDE - each argument as std::formatter<T,...