2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file debug.cpp Handling of printing debug messages. */
11 #include "console_func.h"
13 #include "string_func.h"
14 #include "fileio_func.h"
15 #include "settings_type.h"
19 #include "os/windows/win32.h"
22 #include "3rdparty/fmt/chrono.h"
24 #include "network/network_admin.h"
26 #include "safeguards.h"
28 /** Element in the queue of debug messages that have to be passed to either NetworkAdminConsole or IConsolePrint.*/
29 struct QueuedDebugItem
{
30 std::string level
; ///< The used debug level.
31 std::string message
; ///< The actual formatted message.
33 std::atomic
<bool> _debug_remote_console
; ///< Whether we need to send data to either NetworkAdminConsole or IConsolePrint.
34 std::mutex _debug_remote_console_mutex
; ///< Mutex to guard the queue of debug messages for either NetworkAdminConsole or IConsolePrint.
35 std::vector
<QueuedDebugItem
> _debug_remote_console_queue
; ///< Queue for debug messages to be passed to NetworkAdminConsole or IConsolePrint.
36 std::vector
<QueuedDebugItem
> _debug_remote_console_queue_spare
; ///< Spare queue to swap with _debug_remote_console_queue.
38 int _debug_driver_level
;
41 int _debug_misc_level
;
43 int _debug_sprite_level
;
44 int _debug_oldloader_level
;
46 int _debug_yapf_level
;
47 int _debug_fontcache_level
;
48 int _debug_script_level
;
50 int _debug_gamelog_level
;
51 int _debug_desync_level
;
52 int _debug_console_level
;
54 int _debug_random_level
;
62 #define DEBUG_LEVEL(x) { #x, &_debug_##x##_level }
63 static const DebugLevel debug_level
[] = {
70 DEBUG_LEVEL(oldloader
),
73 DEBUG_LEVEL(fontcache
),
86 * Dump the available debug facility names in the help text.
87 * @param output_iterator The iterator to write the string to.
89 void DumpDebugFacilityNames(std::back_insert_iterator
<std::string
> &output_iterator
)
92 for (const DebugLevel
*i
= debug_level
; i
!= endof(debug_level
); ++i
) {
94 fmt::format_to(output_iterator
, "List of debug facility names:\n");
96 fmt::format_to(output_iterator
, ", ");
98 fmt::format_to(output_iterator
, "{}", i
->name
);
102 fmt::format_to(output_iterator
, "\n\n");
107 * Internal function for outputting the debug line.
108 * @param level Debug category.
109 * @param message The message to output.
111 void DebugPrint(const char *category
, int level
, const std::string
&message
)
113 if (strcmp(category
, "desync") == 0) {
114 static FILE *f
= FioFOpenFile("commands-out.log", "wb", AUTOSAVE_DIR
);
115 if (f
== nullptr) return;
117 fmt::print(f
, "{}{}\n", GetLogPrefix(true), message
);
120 } else if (strcmp(category
, "random") == 0) {
121 static FILE *f
= FioFOpenFile("random-out.log", "wb", AUTOSAVE_DIR
);
122 if (f
== nullptr) return;
124 fmt::print(f
, "{}\n", message
);
128 fmt::print(stderr
, "{}dbg: [{}:{}] {}\n", GetLogPrefix(true), category
, level
, message
);
130 if (_debug_remote_console
.load()) {
131 /* Only add to the queue when there is at least one consumer of the data. */
132 std::lock_guard
<std::mutex
> lock(_debug_remote_console_mutex
);
133 _debug_remote_console_queue
.push_back({ category
, message
});
139 * Set debugging levels by parsing the text in \a s.
140 * For setting individual levels a string like \c "net=3,grf=6" should be used.
141 * If the string starts with a number, the number is used as global debugging level.
142 * @param s Text describing the wanted debugging levels.
143 * @param error_func The function to call if a parse error occurs.
145 void SetDebugString(const char *s
, void (*error_func
)(const std::string
&))
151 /* Store planned changes into map during parse */
152 std::map
<const char *, int> new_levels
;
154 /* Global debugging level? */
155 if (*s
>= '0' && *s
<= '9') {
158 v
= std::strtoul(s
, &end
, 0);
161 for (i
= debug_level
; i
!= endof(debug_level
); ++i
) {
162 new_levels
[i
->name
] = v
;
166 /* Individual levels */
168 /* skip delimiters */
169 while (*s
== ' ' || *s
== ',' || *s
== '\t') s
++;
170 if (*s
== '\0') break;
173 while (*s
>= 'a' && *s
<= 'z') s
++;
175 /* check debugging levels */
176 const DebugLevel
*found
= nullptr;
177 for (const DebugLevel
*i
= debug_level
; i
!= endof(debug_level
); ++i
) {
178 if (s
== t
+ strlen(i
->name
) && strncmp(t
, i
->name
, s
- t
) == 0) {
185 v
= std::strtoul(s
, &end
, 0);
187 if (found
!= nullptr) {
188 new_levels
[found
->name
] = v
;
190 std::string error_string
= fmt::format("Unknown debug level '{}'", std::string(t
, s
- t
));
191 error_func(error_string
);
196 /* Apply the changes after parse is successful */
197 for (const DebugLevel
*i
= debug_level
; i
!= endof(debug_level
); ++i
) {
198 const auto &nl
= new_levels
.find(i
->name
);
199 if (nl
!= new_levels
.end()) {
200 *i
->level
= nl
->second
;
206 * Print out the current debug-level.
207 * Just return a string with the values of all the debug categories.
208 * @return string with debug-levels
210 std::string
GetDebugString()
213 for (const DebugLevel
*i
= debug_level
; i
!= endof(debug_level
); ++i
) {
214 if (!result
.empty()) result
+= ", ";
215 fmt::format_to(std::back_inserter(result
), "{}={}", i
->name
, *i
->level
);
221 * Get the prefix for logs.
223 * If show_date_in_logs or \p force is enabled it returns
224 * the date, otherwise it returns an empty string.
226 * @return the prefix for logs.
228 std::string
GetLogPrefix(bool force
)
230 std::string log_prefix
;
231 if (force
|| _settings_client
.gui
.show_date_in_logs
) {
232 log_prefix
= fmt::format("[{:%Y-%m-%d %H:%M:%S}] ", fmt::localtime(time(nullptr)));
238 * Send the queued Debug messages to either NetworkAdminConsole or IConsolePrint from the
239 * GameLoop thread to prevent concurrent accesses to both the NetworkAdmin's packet queue
240 * as well as IConsolePrint's buffers.
242 * This is to be called from the GameLoop thread.
244 void DebugSendRemoteMessages()
246 if (!_debug_remote_console
.load()) return;
249 std::lock_guard
<std::mutex
> lock(_debug_remote_console_mutex
);
250 std::swap(_debug_remote_console_queue
, _debug_remote_console_queue_spare
);
253 for (auto &item
: _debug_remote_console_queue_spare
) {
254 NetworkAdminConsole(item
.level
, item
.message
);
255 if (_settings_client
.gui
.developer
>= 2) IConsolePrint(CC_DEBUG
, "dbg: [{}] {}", item
.level
, item
.message
);
258 _debug_remote_console_queue_spare
.clear();
262 * Reconsider whether we need to send debug messages to either NetworkAdminConsole
263 * or IConsolePrint. The former is when they have enabled console handling whereas
264 * the latter depends on the gui.developer setting's value.
266 * This is to be called from the GameLoop thread.
268 void DebugReconsiderSendRemoteMessages()
270 bool enable
= _settings_client
.gui
.developer
>= 2;
272 for (ServerNetworkAdminSocketHandler
*as
: ServerNetworkAdminSocketHandler::IterateActive()) {
273 if (as
->update_frequency
[ADMIN_UPDATE_CONSOLE
] & ADMIN_FREQUENCY_AUTOMATIC
) {
279 _debug_remote_console
.store(enable
);