Debian Codegraph @

common/Logging.cpp

raw
1 /*
2 * Logging.cpp
3 * -----------
4 * Purpose: General logging
5 * Notes : (currently none)
6 * Authors: OpenMPT Devs
7 * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
8 */
9
10
11 #include "stdafx.h"
12
13 #include "Logging.h"
14
15 #include "mpt/base/macros.hpp"
16 #include "mpt/io/base.hpp"
17 #include "mpt/io/io.hpp"
18 #include "mpt/io/io_stdstream.hpp"
19 #if defined(MODPLUG_TRACKER)
20 #include "mpt/io_file/fstream.hpp"
21 #endif
22
23 #if defined(MODPLUG_TRACKER)
24 #include "mptFileIO.h"
25 #endif
26
27 #if defined(MODPLUG_TRACKER)
28 #include <atomic>
29 #endif
30 #include "version.h"
31
32 #include <iostream>
33
34 #include <cstdarg>
35 #include <cstring>
36
37 #include <stdarg.h>
38
39
40 OPENMPT_NAMESPACE_BEGIN
41
42
43 namespace mpt
44 {
45 namespace log
46 {
47
48
49
50 #if !defined(MPT_LOG_GLOBAL_LEVEL_STATIC)
51 #if defined(MPT_LOG_GLOBAL_LEVEL)
52 MPT_CONSTINIT int GlobalLogLevel = static_cast<int>(MPT_LOG_GLOBAL_LEVEL);
53 #else
54 MPT_CONSTINIT int GlobalLogLevel = static_cast<int>(LogDebug);
55 #endif
56 #endif
57
58
59
60 #if defined(MODPLUG_TRACKER) && !defined(MPT_LOG_IS_DISABLED)
61
62 MPT_CONSTINIT bool FileEnabled = false;
63 MPT_CONSTINIT bool DebuggerEnabled = true;
64 MPT_CONSTINIT bool ConsoleEnabled = false;
65
66 static MPT_CONSTINIT char g_FacilitySolo[1024] = {0};
67 static MPT_CONSTINIT char g_FacilityBlocked[1024] = {0};
68
69 void SetFacilities(const std::string &solo, const std::string &blocked)
70 {
71 std::strcpy(g_FacilitySolo, solo.c_str());
72 std::strcpy(g_FacilityBlocked, blocked.c_str());
73 }
74
75 bool IsFacilityActive(const char *facility) noexcept
76 {
77 if(facility)
78 {
79 if(std::strlen(g_FacilitySolo) > 0)
80 {
81 if(std::strcmp(facility, g_FacilitySolo) != 0)
82 {
83 return false;
84 }
85 }
86 if(std::strlen(g_FacilityBlocked) > 0)
87 {
88 if(std::strcmp(facility, g_FacilitySolo) == 0)
89 {
90 return false;
91 }
92 }
93 }
94 return true;
95 }
96
97 #endif
98
99
100 void GlobalLogger::SendLogMessage(const mpt::source_location &loc, LogLevel level, const char *facility, const mpt::ustring &text) const
101 {
102 #ifdef MPT_LOG_IS_DISABLED
103 MPT_UNREFERENCED_PARAMETER(loc);
104 MPT_UNREFERENCED_PARAMETER(level);
105 MPT_UNREFERENCED_PARAMETER(facility);
106 MPT_UNREFERENCED_PARAMETER(text);
107 #else // !MPT_LOG_IS_DISABLED
108 MPT_MAYBE_CONSTANT_IF(mpt::log::GlobalLogLevel < level)
109 {
110 return;
111 }
112 #if defined(MODPLUG_TRACKER)
113 if(!IsFacilityActive(facility))
114 {
115 return;
116 }
117 #else // !MODPLUG_TRACKER
118 MPT_UNREFERENCED_PARAMETER(facility);
119 #endif // MODPLUG_TRACKER
120 // remove eol if already present and add log level prefix
121 const mpt::ustring message = LogLevelToString(level) + U_(": ") + mpt::trim_right(text, U_("\r\n"));
122 const mpt::ustring file = mpt::transcode<mpt::ustring>(mpt::source_encoding, loc.file_name() ? loc.file_name() : "");
123 const mpt::ustring function = mpt::transcode<mpt::ustring>(mpt::source_encoding, loc.function_name() ? loc.function_name() : "");
124 const mpt::ustring line = mpt::ufmt::dec(loc.line());
125 #if defined(MODPLUG_TRACKER) && !defined(MPT_BUILD_WINESUPPORT)
126 #if MPT_OS_WINDOWS
127 static uint64 s_lastlogtime = 0;
128 uint64 cur = mpt::Date::ANSI::Now();
129 uint64 diff = cur/10000 - s_lastlogtime;
130 s_lastlogtime = cur/10000;
131 #else
132 uint64 cur = 0;
133 uint64 diff = 0;
134 #endif
135 if(mpt::log::FileEnabled)
136 {
137 static std::optional<mpt::IO::ofstream> s_logfile;
138 if(!s_logfile)
139 {
140 s_logfile.emplace(P_("mptrack.log"), std::ios::app);
141 }
142 if(s_logfile)
143 {
144 mpt::IO::WriteText(*s_logfile, mpt::transcode<std::string>(mpt::logfile_encoding, MPT_UFORMAT("{}+{} {}({}): {} [{}]\n")
145 ( mpt::Date::ANSI::ToUString(cur)
146 , mpt::ufmt::right(6, mpt::ufmt::dec(diff))
147 , file
148 , line
149 , message
150 , function
151 )));
152 mpt::IO::Flush(*s_logfile);
153 }
154 }
155 if(mpt::log::DebuggerEnabled)
156 {
157 OutputDebugStringW(mpt::ToWide(MPT_UFORMAT("{}({}): +{} {} [{}]\n")
158 ( file
159 , line
160 , mpt::ufmt::right(6, mpt::ufmt::dec(diff))
161 , message
162 , function
163 )).c_str());
164 }
165 if(mpt::log::ConsoleEnabled)
166 {
167 static bool consoleInited = false;
168 if(!consoleInited)
169 {
170 AllocConsole();
171 consoleInited = true;
172 }
173 std::wstring consoletext = mpt::ToWide(message) + L"\r\n";
174 DWORD dummy = 0;
175 WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), consoletext.c_str(), mpt::saturate_cast<DWORD>(consoletext.length()), &dummy, NULL);
176 }
177 #elif defined(MODPLUG_TRACKER) && defined(MPT_BUILD_WINESUPPORT)
178 std::clog
179 << "NativeSupport: "
180 << mpt::transcode<std::string>(mpt::stdio_encoding, file) << "(" << mpt::transcode<std::string>(mpt::stdio_encoding, line) << ")" << ": "
181 << mpt::transcode<std::string>(mpt::stdio_encoding, message)
182 << " [" << mpt::transcode<std::string>(mpt::stdio_encoding, function) << "]"
183 << std::endl;
184 #else // !MODPLUG_TRACKER
185 std::clog
186 << "libopenmpt: "
187 << mpt::transcode<std::string>(mpt::stdio_encoding, file) << "(" << mpt::transcode<std::string>(mpt::stdio_encoding, line) << ")" << ": "
188 << mpt::transcode<std::string>(mpt::stdio_encoding, message)
189 << " [" << mpt::transcode<std::string>(mpt::stdio_encoding, function) << "]"
190 << std::endl;
191 #endif // MODPLUG_TRACKER
192 #endif // MPT_LOG_IS_DISABLED
193 }
194
195
196
197 #if defined(MODPLUG_TRACKER)
198
199 namespace Trace {
200
201 #if MPT_OS_WINDOWS
202
203 // Debugging functionality will use simple globals.
204
205 MPT_CONSTINIT std::atomic<bool> g_Enabled{false};
206
207 static MPT_CONSTINIT bool g_Sealed = false;
208
209 struct Entry {
210 uint32 Index;
211 uint32 ThreadId;
212 uint64 Timestamp;
213 const char * Function;
214 const char * File;
215 int Line;
216 Direction Direction;
217 };
218
219 static MPT_FORCEINLINE bool operator < (const Entry &a, const Entry &b) noexcept
220 {
221 /*
222 return false
223 || (a.Timestamp < b.Timestamp)
224 || (a.ThreadID < b.ThreadID)
225 || (a.File < b.File)
226 || (a.Line < b.Line)
227 || (a.Function < b.Function)
228 ;
229 */
230 return false
231 || (a.Index < b.Index)
232 ;
233 }
234
235 #if MPT_COMPILER_MSVC
236 // VS2022 still does nto have constexpr vector default ctor
237 static /*MPT_CONSTINIT*/ std::vector<mpt::log::Trace::Entry> Entries;
238 #else
239 static MPT_CONSTINIT std::vector<mpt::log::Trace::Entry> Entries;
240 #endif
241
242 static MPT_CONSTINIT std::atomic<uint32> NextIndex(0);
243
244 static MPT_CONSTINIT uint32 ThreadIdGUI = 0;
245 static MPT_CONSTINIT uint32 ThreadIdAudio = 0;
246 static MPT_CONSTINIT uint32 ThreadIdNotify = 0;
247 static MPT_CONSTINIT uint32 ThreadIdWatchdir = 0;
248
249 void Enable(std::size_t numEntries)
250 {
251 if(g_Sealed)
252 {
253 return;
254 }
255 Entries.clear();
256 Entries.resize(numEntries);
257 NextIndex.store(0);
258 g_Enabled = (numEntries > 0);
259 }
260
261 void Disable()
262 {
263 if(g_Sealed)
264 {
265 return;
266 }
267 g_Enabled = false;
268 }
269
270 MPT_NOINLINE void Trace(const mpt::source_location & loc, Direction direction) noexcept
271 {
272 // This will get called in realtime contexts and hot paths.
273 // No blocking allowed here.
274 const uint32 index = NextIndex.fetch_add(1);
275 const std::size_t numEntries = Entries.size();
276 #if 1
277 LARGE_INTEGER time;
278 time.QuadPart = 0;
279 QueryPerformanceCounter(&time);
280 const uint64 timestamp = time.QuadPart;
281 #else
282 FILETIME time = FILETIME();
283 GetSystemTimeAsFileTime(&time);
284 const uint64 timestamp = (static_cast<uint64>(time.dwHighDateTime) << 32) | (static_cast<uint64>(time.dwLowDateTime) << 0);
285 #endif
286 const uint32 threadid = static_cast<uint32>(GetCurrentThreadId());
287 mpt::log::Trace::Entry & entry = Entries[index % numEntries];
288 entry.Index = index;
289 entry.ThreadId = threadid;
290 entry.Timestamp = timestamp;
291 entry.Function = loc.function_name();
292 entry.File = loc.file_name();
293 entry.Line = loc.line();
294 entry.Direction = direction;
295 }
296
297 void Seal()
298 {
299 if(!g_Enabled)
300 {
301 return;
302 }
303 g_Enabled = false;
304 g_Sealed = true;
305 uint32 count = NextIndex.fetch_add(0);
306 if(count < Entries.size())
307 {
308 Entries.resize(count);
309 }
310 }
311
312 bool Dump(const mpt::PathString &filename)
313 {
314 if(!g_Sealed)
315 {
316 return false;
317 }
318
319 LARGE_INTEGER qpcNow;
320 qpcNow.QuadPart = 0;
321 QueryPerformanceCounter(&qpcNow);
322 uint64 ftNow = mpt::Date::ANSI::Now();
323
324 // sort according to index in case of overflows
325 std::stable_sort(Entries.begin(), Entries.end());
326
327 mpt::IO::ofstream f(filename);
328
329 f << "Build: OpenMPT " << mpt::transcode<std::string>(mpt::logfile_encoding, Build::GetVersionStringExtended()) << std::endl;
330
331 bool qpcValid = false;
332
333 LARGE_INTEGER qpcFreq;
334 qpcFreq.QuadPart = 0;
335 QueryPerformanceFrequency(&qpcFreq);
336 if(qpcFreq.QuadPart > 0)
337 {
338 qpcValid = true;
339 }
340
341 f << "Dump: " << mpt::transcode<std::string>(mpt::logfile_encoding, mpt::Date::ANSI::ToUString(ftNow)) << std::endl;
342 f << "Captured events: " << Entries.size() << std::endl;
343 if(qpcValid && (Entries.size() > 0))
344 {
345 double period = static_cast<double>(Entries[Entries.size() - 1].Timestamp - Entries[0].Timestamp) / static_cast<double>(qpcFreq.QuadPart);
346 double eventsPerSecond = Entries.size() / period;
347 f << "Period [s]: " << mpt::afmt::fix(period) << std::endl;
348 f << "Events/second: " << mpt::afmt::fix(eventsPerSecond) << std::endl;
349 }
350
351 for(auto &entry : Entries)
352 {
353 if(!entry.Function) entry.Function = "";
354 if(!entry.File) entry.File = "";
355 std::string time;
356 if(qpcValid)
357 {
358 time = mpt::transcode<std::string>(mpt::logfile_encoding, mpt::Date::ANSI::ToUString( ftNow - static_cast<int64>( static_cast<double>(qpcNow.QuadPart - entry.Timestamp) * (10000000.0 / static_cast<double>(qpcFreq.QuadPart) ) ) ) );
359 } else
360 {
361 time = MPT_AFORMAT("0x{}")(mpt::afmt::hex0<16>(entry.Timestamp));
362 }
363 f << time;
364 if(entry.ThreadId == ThreadIdGUI)
365 {
366 f << " -----GUI ";
367 } else if(entry.ThreadId == ThreadIdAudio)
368 {
369 f << " ---Audio ";
370 } else if(entry.ThreadId == ThreadIdNotify)
371 {
372 f << " --Notify ";
373 } else if(entry.ThreadId == ThreadIdWatchdir)
374 {
375 f << " WatchDir ";
376 } else
377 {
378 f << " " << mpt::afmt::hex0<8>(entry.ThreadId) << " ";
379 }
380 f << (entry.Direction == mpt::log::Trace::Direction::Enter ? ">" : entry.Direction == mpt::log::Trace::Direction::Leave ? "<" : " ") << " ";
381 f << entry.File << "(" << entry.Line << "): " << entry.Function;
382 f << std::endl;
383 }
384 return true;
385 }
386
387 void SetThreadId(mpt::log::Trace::ThreadKind kind, uint32 id)
388 {
389 if(id == 0)
390 {
391 return;
392 }
393 switch(kind)
394 {
395 case ThreadKindGUI:
396 ThreadIdGUI = id;
397 break;
398 case ThreadKindAudio:
399 ThreadIdAudio = id;
400 break;
401 case ThreadKindNotify:
402 ThreadIdNotify = id;
403 break;
404 case ThreadKindWatchdir:
405 ThreadIdWatchdir = id;
406 break;
407 }
408 }
409
410 uint32 GetThreadId(mpt::log::Trace::ThreadKind kind)
411 {
412 uint32 result = 0;
413 switch(kind)
414 {
415 case ThreadKindGUI:
416 result = ThreadIdGUI;
417 break;
418 case ThreadKindAudio:
419 result = ThreadIdAudio;
420 break;
421 case ThreadKindNotify:
422 result = ThreadIdNotify;
423 break;
424 case ThreadKindWatchdir:
425 result = ThreadIdWatchdir;
426 break;
427 }
428 return result;
429 }
430
431 #endif // MPT_OS_WINDOWS
432
433 } // namespace Trace
434
435 #endif // MODPLUG_TRACKER
436
437
438 } // namespace log
439 } // namespace mpt
440
441
442 OPENMPT_NAMESPACE_END