Update: Translations from eints
[openttd-github.git] / src / debug.cpp
blob5c33cc8ff007fda881c90d96e76028bd3257b7a6
1 /*
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/>.
6 */
8 /** @file debug.cpp Handling of printing debug messages. */
10 #include "stdafx.h"
11 #include "console_func.h"
12 #include "debug.h"
13 #include "string_func.h"
14 #include "fileio_func.h"
15 #include "settings_type.h"
16 #include <mutex>
18 #if defined(_WIN32)
19 #include "os/windows/win32.h"
20 #endif
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;
39 int _debug_grf_level;
40 int _debug_map_level;
41 int _debug_misc_level;
42 int _debug_net_level;
43 int _debug_sprite_level;
44 int _debug_oldloader_level;
45 int _debug_yapf_level;
46 int _debug_fontcache_level;
47 int _debug_script_level;
48 int _debug_sl_level;
49 int _debug_gamelog_level;
50 int _debug_desync_level;
51 int _debug_console_level;
52 #ifdef RANDOM_DEBUG
53 int _debug_random_level;
54 #endif
56 struct DebugLevel {
57 const char *name;
58 int *level;
61 #define DEBUG_LEVEL(x) { #x, &_debug_##x##_level }
62 static const DebugLevel _debug_levels[] = {
63 DEBUG_LEVEL(driver),
64 DEBUG_LEVEL(grf),
65 DEBUG_LEVEL(map),
66 DEBUG_LEVEL(misc),
67 DEBUG_LEVEL(net),
68 DEBUG_LEVEL(sprite),
69 DEBUG_LEVEL(oldloader),
70 DEBUG_LEVEL(yapf),
71 DEBUG_LEVEL(fontcache),
72 DEBUG_LEVEL(script),
73 DEBUG_LEVEL(sl),
74 DEBUG_LEVEL(gamelog),
75 DEBUG_LEVEL(desync),
76 DEBUG_LEVEL(console),
77 #ifdef RANDOM_DEBUG
78 DEBUG_LEVEL(random),
79 #endif
81 #undef DEBUG_LEVEL
83 /**
84 * Dump the available debug facility names in the help text.
85 * @param output_iterator The iterator to write the string to.
87 void DumpDebugFacilityNames(std::back_insert_iterator<std::string> &output_iterator)
89 bool written = false;
90 for (const auto &debug_level : _debug_levels) {
91 if (!written) {
92 fmt::format_to(output_iterator, "List of debug facility names:\n");
93 } else {
94 fmt::format_to(output_iterator, ", ");
96 fmt::format_to(output_iterator, "{}", debug_level.name);
97 written = true;
99 if (written) {
100 fmt::format_to(output_iterator, "\n\n");
105 * Internal function for outputting the debug line.
106 * @param level Debug category.
107 * @param message The message to output.
109 void DebugPrint(const char *category, int level, const std::string &message)
111 if (strcmp(category, "desync") == 0 && level != 0) {
112 static auto f = FioFOpenFile("commands-out.log", "wb", AUTOSAVE_DIR);
113 if (!f.has_value()) return;
115 fmt::print(*f, "{}{}\n", GetLogPrefix(true), message);
116 fflush(*f);
117 #ifdef RANDOM_DEBUG
118 } else if (strcmp(category, "random") == 0) {
119 static auto f = FioFOpenFile("random-out.log", "wb", AUTOSAVE_DIR);
120 if (!f.has_value()) return;
122 fmt::print(*f, "{}\n", message);
123 fflush(*f);
124 #endif
125 } else {
126 fmt::print(stderr, "{}dbg: [{}:{}] {}\n", GetLogPrefix(true), category, level, message);
128 if (_debug_remote_console.load()) {
129 /* Only add to the queue when there is at least one consumer of the data. */
130 std::lock_guard<std::mutex> lock(_debug_remote_console_mutex);
131 _debug_remote_console_queue.push_back({ category, message });
137 * Set debugging levels by parsing the text in \a s.
138 * For setting individual levels a string like \c "net=3,grf=6" should be used.
139 * If the string starts with a number, the number is used as global debugging level.
140 * @param s Text describing the wanted debugging levels.
141 * @param error_func The function to call if a parse error occurs.
143 void SetDebugString(const char *s, void (*error_func)(const std::string &))
145 int v;
146 char *end;
147 const char *t;
149 /* Store planned changes into map during parse */
150 std::map<const char *, int> new_levels;
152 /* Global debugging level? */
153 if (*s >= '0' && *s <= '9') {
154 v = std::strtoul(s, &end, 0);
155 s = end;
157 for (const auto &debug_level : _debug_levels) {
158 new_levels[debug_level.name] = v;
162 /* Individual levels */
163 for (;;) {
164 /* skip delimiters */
165 while (*s == ' ' || *s == ',' || *s == '\t') s++;
166 if (*s == '\0') break;
168 t = s;
169 while (*s >= 'a' && *s <= 'z') s++;
171 /* check debugging levels */
172 const DebugLevel *found = nullptr;
173 for (const auto &debug_level : _debug_levels) {
174 if (s == t + strlen(debug_level.name) && strncmp(t, debug_level.name, s - t) == 0) {
175 found = &debug_level;
176 break;
180 if (*s == '=') s++;
181 v = std::strtoul(s, &end, 0);
182 s = end;
183 if (found != nullptr) {
184 new_levels[found->name] = v;
185 } else {
186 std::string error_string = fmt::format("Unknown debug level '{}'", std::string(t, s - t));
187 error_func(error_string);
188 return;
192 /* Apply the changes after parse is successful */
193 for (const auto &debug_level : _debug_levels) {
194 const auto &nl = new_levels.find(debug_level.name);
195 if (nl != new_levels.end()) {
196 *debug_level.level = nl->second;
202 * Print out the current debug-level.
203 * Just return a string with the values of all the debug categories.
204 * @return string with debug-levels
206 std::string GetDebugString()
208 std::string result;
209 for (const auto &debug_level : _debug_levels) {
210 if (!result.empty()) result += ", ";
211 fmt::format_to(std::back_inserter(result), "{}={}", debug_level.name, *debug_level.level);
213 return result;
217 * Get the prefix for logs.
219 * If show_date_in_logs or \p force is enabled it returns
220 * the date, otherwise it returns an empty string.
222 * @return the prefix for logs.
224 std::string GetLogPrefix(bool force)
226 std::string log_prefix;
227 if (force || _settings_client.gui.show_date_in_logs) {
228 log_prefix = fmt::format("[{:%Y-%m-%d %H:%M:%S}] ", fmt::localtime(time(nullptr)));
230 return log_prefix;
234 * Send the queued Debug messages to either NetworkAdminConsole or IConsolePrint from the
235 * GameLoop thread to prevent concurrent accesses to both the NetworkAdmin's packet queue
236 * as well as IConsolePrint's buffers.
238 * This is to be called from the GameLoop thread.
240 void DebugSendRemoteMessages()
242 if (!_debug_remote_console.load()) return;
245 std::lock_guard<std::mutex> lock(_debug_remote_console_mutex);
246 std::swap(_debug_remote_console_queue, _debug_remote_console_queue_spare);
249 for (auto &item : _debug_remote_console_queue_spare) {
250 NetworkAdminConsole(item.level, item.message);
251 if (_settings_client.gui.developer >= 2) IConsolePrint(CC_DEBUG, "dbg: [{}] {}", item.level, item.message);
254 _debug_remote_console_queue_spare.clear();
258 * Reconsider whether we need to send debug messages to either NetworkAdminConsole
259 * or IConsolePrint. The former is when they have enabled console handling whereas
260 * the latter depends on the gui.developer setting's value.
262 * This is to be called from the GameLoop thread.
264 void DebugReconsiderSendRemoteMessages()
266 bool enable = _settings_client.gui.developer >= 2;
268 for (ServerNetworkAdminSocketHandler *as : ServerNetworkAdminSocketHandler::IterateActive()) {
269 if (as->update_frequency[ADMIN_UPDATE_CONSOLE] & ADMIN_FREQUENCY_AUTOMATIC) {
270 enable = true;
271 break;
275 _debug_remote_console.store(enable);