Debian Codegraph @

core/io/logger.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* logger.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "logger.h"
32
33 #include "core/core_globals.h"
34 #include "core/io/dir_access.h"
35 #include "core/io/file_access.h"
36 #include "core/object/script_backtrace.h"
37 #include "core/os/time.h"
38 #include "core/templates/rb_set.h"
39
40 #include "modules/modules_enabled.gen.h" // For regex.
41
42 #ifdef MODULE_REGEX_ENABLED
43 #include "modules/regex/regex.h"
44 #endif // MODULE_REGEX_ENABLED
45
46 #if defined(MINGW_ENABLED) || defined(_MSC_VER)
47 #define sprintf sprintf_s
48 #endif
49
50 bool Logger::should_log(bool p_err) {
51 return (!p_err || CoreGlobals::print_error_enabled) && (p_err || CoreGlobals::print_line_enabled);
52 }
53
54 void Logger::set_flush_stdout_on_print(bool value) {
55 _flush_stdout_on_print = value;
56 }
57
58 void Logger::log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify, ErrorType p_type, const Vector<Ref<ScriptBacktrace>> &p_script_backtraces) {
59 if (!should_log(true)) {
60 return;
61 }
62
63 const char *err_type = error_type_string(p_type);
64
65 const char *err_details;
66 if (p_rationale && *p_rationale) {
67 err_details = p_rationale;
68 } else {
69 err_details = p_code;
70 }
71
72 logf_error("%s: %s\n", err_type, err_details);
73 logf_error(" at: %s (%s:%i)\n", p_function, p_file, p_line);
74
75 for (const Ref<ScriptBacktrace> &backtrace : p_script_backtraces) {
76 if (!backtrace->is_empty()) {
77 logf_error("%s\n", backtrace->format(3).utf8().get_data());
78 }
79 }
80 }
81
82 void Logger::logf(const char *p_format, ...) {
83 if (!should_log(false)) {
84 return;
85 }
86
87 va_list argp;
88 va_start(argp, p_format);
89
90 logv(p_format, argp, false);
91
92 va_end(argp);
93 }
94
95 void Logger::logf_error(const char *p_format, ...) {
96 if (!should_log(true)) {
97 return;
98 }
99
100 va_list argp;
101 va_start(argp, p_format);
102
103 logv(p_format, argp, true);
104
105 va_end(argp);
106 }
107
108 void RotatedFileLogger::clear_old_backups() {
109 int max_backups = max_files - 1; // -1 for the current file
110
111 String basename = base_path.get_file().get_basename();
112 String extension = base_path.get_extension();
113
114 Ref<DirAccess> da = DirAccess::open(base_path.get_base_dir());
115 if (da.is_null()) {
116 return;
117 }
118
119 da->list_dir_begin();
120 String f = da->get_next();
121 // backups is a RBSet because it guarantees that iterating on it is done in sorted order.
122 // RotatedFileLogger depends on this behavior to delete the oldest log file first.
123 RBSet<String> backups;
124 while (!f.is_empty()) {
125 if (!da->current_is_dir() && f.begins_with(basename) && f.get_extension() == extension && f != base_path.get_file()) {
126 backups.insert(f);
127 }
128 f = da->get_next();
129 }
130 da->list_dir_end();
131
132 if (backups.size() > max_backups) {
133 // since backups are appended with timestamp and Set iterates them in sorted order,
134 // first backups are the oldest
135 int to_delete = backups.size() - max_backups;
136 for (RBSet<String>::Element *E = backups.front(); E && to_delete > 0; E = E->next(), --to_delete) {
137 da->remove(E->get());
138 }
139 }
140 }
141
142 void RotatedFileLogger::rotate_file() {
143 file.unref();
144
145 if (FileAccess::exists(base_path)) {
146 if (max_files > 1) {
147 String timestamp = Time::get_singleton()->get_datetime_string_from_system().replace_char(':', '.');
148 String backup_name = base_path.get_basename() + timestamp;
149 if (!base_path.get_extension().is_empty()) {
150 backup_name += "." + base_path.get_extension();
151 }
152
153 Ref<DirAccess> da = DirAccess::open(base_path.get_base_dir());
154 if (da.is_valid()) {
155 da->copy(base_path, backup_name);
156 }
157 clear_old_backups();
158 }
159 } else {
160 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_USERDATA);
161 if (da.is_valid()) {
162 da->make_dir_recursive(base_path.get_base_dir());
163 }
164 }
165
166 file = FileAccess::open(base_path, FileAccess::WRITE);
167 file->detach_from_objectdb(); // Note: This FileAccess instance will exist longer than ObjectDB, therefore can't be registered in ObjectDB.
168 }
169
170 RotatedFileLogger::RotatedFileLogger(const String &p_base_path, int p_max_files) :
171 base_path(p_base_path.simplify_path()),
172 max_files(p_max_files > 0 ? p_max_files : 1) {
173 rotate_file();
174
175 #ifdef MODULE_REGEX_ENABLED
176 strip_ansi_regex.instantiate();
177 strip_ansi_regex->detach_from_objectdb(); // Note: This RegEx instance will exist longer than ObjectDB, therefore can't be registered in ObjectDB.
178 strip_ansi_regex->compile("\u001b\\[((?:\\d|;)*)([a-zA-Z])");
179 #endif // MODULE_REGEX_ENABLED
180 }
181
182 void RotatedFileLogger::logv(const char *p_format, va_list p_list, bool p_err) {
183 if (!should_log(p_err)) {
184 return;
185 }
186
187 if (file.is_valid()) {
188 const int static_buf_size = 512;
189 char static_buf[static_buf_size];
190 char *buf = static_buf;
191 va_list list_copy;
192 va_copy(list_copy, p_list);
193 int len = vsnprintf(buf, static_buf_size, p_format, p_list);
194 if (len >= static_buf_size) {
195 buf = (char *)Memory::alloc_static(len + 1);
196 vsnprintf(buf, len + 1, p_format, list_copy);
197 }
198 va_end(list_copy);
199
200 #ifdef MODULE_REGEX_ENABLED
201 // Strip ANSI escape codes (such as those inserted by `print_rich()`)
202 // before writing to file, as text editors cannot display those
203 // correctly.
204 file->store_string(strip_ansi_regex->sub(String::utf8(buf), "", true));
205 #else
206 file->store_buffer((uint8_t *)buf, len);
207 #endif // MODULE_REGEX_ENABLED
208
209 if (len >= static_buf_size) {
210 Memory::free_static(buf);
211 }
212
213 if (p_err || _flush_stdout_on_print) {
214 // Don't always flush when printing stdout to avoid performance
215 // issues when `print()` is spammed in release builds.
216 file->flush();
217 }
218 }
219 }
220
221 void StdLogger::logv(const char *p_format, va_list p_list, bool p_err) {
222 if (!should_log(p_err)) {
223 return;
224 }
225
226 if (p_err) {
227 vfprintf(stderr, p_format, p_list);
228 } else {
229 vprintf(p_format, p_list);
230 if (_flush_stdout_on_print) {
231 // Don't always flush when printing stdout to avoid performance
232 // issues when `print()` is spammed in release builds.
233 fflush(stdout);
234 }
235 }
236 }
237
238 CompositeLogger::CompositeLogger(const Vector<Logger *> &p_loggers) :
239 loggers(p_loggers) {
240 }
241
242 void CompositeLogger::logv(const char *p_format, va_list p_list, bool p_err) {
243 if (!should_log(p_err)) {
244 return;
245 }
246
247 for (int i = 0; i < loggers.size(); ++i) {
248 va_list list_copy;
249 va_copy(list_copy, p_list);
250 loggers[i]->logv(p_format, list_copy, p_err);
251 va_end(list_copy);
252 }
253 }
254
255 void CompositeLogger::log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify, ErrorType p_type, const Vector<Ref<ScriptBacktrace>> &p_script_backtraces) {
256 if (!should_log(true)) {
257 return;
258 }
259
260 for (int i = 0; i < loggers.size(); ++i) {
261 loggers[i]->log_error(p_function, p_file, p_line, p_code, p_rationale, p_editor_notify, p_type, p_script_backtraces);
262 }
263 }
264
265 void CompositeLogger::add_logger(Logger *p_logger) {
266 loggers.push_back(p_logger);
267 }
268
269 CompositeLogger::~CompositeLogger() {
270 for (int i = 0; i < loggers.size(); ++i) {
271 memdelete(loggers[i]);
272 }
273 }