2
0

logger.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. #include "logger.h"
  31. #include "core/core_globals.h"
  32. #include "core/io/dir_access.h"
  33. #include "core/os/time.h"
  34. #include "core/templates/rb_set.h"
  35. #include "modules/modules_enabled.gen.h" // For regex.
  36. #ifdef MODULE_REGEX_ENABLED
  37. #include "modules/regex/regex.h"
  38. #endif // MODULE_REGEX_ENABLED
  39. #if defined(MINGW_ENABLED) || defined(_MSC_VER)
  40. #define sprintf sprintf_s
  41. #endif
  42. bool Logger::should_log(bool p_err) {
  43. return (!p_err || CoreGlobals::print_error_enabled) && (p_err || CoreGlobals::print_line_enabled);
  44. }
  45. void Logger::set_flush_stdout_on_print(bool value) {
  46. _flush_stdout_on_print = value;
  47. }
  48. 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) {
  49. if (!should_log(true)) {
  50. return;
  51. }
  52. const char *err_type = error_type_string(p_type);
  53. const char *err_details;
  54. if (p_rationale && *p_rationale) {
  55. err_details = p_rationale;
  56. } else {
  57. err_details = p_code;
  58. }
  59. logf_error("%s: %s\n", err_type, err_details);
  60. logf_error(" at: %s (%s:%i)\n", p_function, p_file, p_line);
  61. for (const Ref<ScriptBacktrace> &backtrace : p_script_backtraces) {
  62. if (!backtrace->is_empty()) {
  63. logf_error("%s\n", backtrace->format(3).utf8().get_data());
  64. }
  65. }
  66. }
  67. void Logger::logf(const char *p_format, ...) {
  68. if (!should_log(false)) {
  69. return;
  70. }
  71. va_list argp;
  72. va_start(argp, p_format);
  73. logv(p_format, argp, false);
  74. va_end(argp);
  75. }
  76. void Logger::logf_error(const char *p_format, ...) {
  77. if (!should_log(true)) {
  78. return;
  79. }
  80. va_list argp;
  81. va_start(argp, p_format);
  82. logv(p_format, argp, true);
  83. va_end(argp);
  84. }
  85. void RotatedFileLogger::clear_old_backups() {
  86. int max_backups = max_files - 1; // -1 for the current file
  87. String basename = base_path.get_file().get_basename();
  88. String extension = base_path.get_extension();
  89. Ref<DirAccess> da = DirAccess::open(base_path.get_base_dir());
  90. if (da.is_null()) {
  91. return;
  92. }
  93. da->list_dir_begin();
  94. String f = da->get_next();
  95. // backups is a RBSet because it guarantees that iterating on it is done in sorted order.
  96. // RotatedFileLogger depends on this behavior to delete the oldest log file first.
  97. RBSet<String> backups;
  98. while (!f.is_empty()) {
  99. if (!da->current_is_dir() && f.begins_with(basename) && f.get_extension() == extension && f != base_path.get_file()) {
  100. backups.insert(f);
  101. }
  102. f = da->get_next();
  103. }
  104. da->list_dir_end();
  105. if (backups.size() > max_backups) {
  106. // since backups are appended with timestamp and Set iterates them in sorted order,
  107. // first backups are the oldest
  108. int to_delete = backups.size() - max_backups;
  109. for (RBSet<String>::Element *E = backups.front(); E && to_delete > 0; E = E->next(), --to_delete) {
  110. da->remove(E->get());
  111. }
  112. }
  113. }
  114. void RotatedFileLogger::rotate_file() {
  115. file.unref();
  116. if (FileAccess::exists(base_path)) {
  117. if (max_files > 1) {
  118. String timestamp = Time::get_singleton()->get_datetime_string_from_system().replace_char(':', '.');
  119. String backup_name = base_path.get_basename() + timestamp;
  120. if (!base_path.get_extension().is_empty()) {
  121. backup_name += "." + base_path.get_extension();
  122. }
  123. Ref<DirAccess> da = DirAccess::open(base_path.get_base_dir());
  124. if (da.is_valid()) {
  125. da->copy(base_path, backup_name);
  126. }
  127. clear_old_backups();
  128. }
  129. } else {
  130. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_USERDATA);
  131. if (da.is_valid()) {
  132. da->make_dir_recursive(base_path.get_base_dir());
  133. }
  134. }
  135. file = FileAccess::open(base_path, FileAccess::WRITE);
  136. file->detach_from_objectdb(); // Note: This FileAccess instance will exist longer than ObjectDB, therefore can't be registered in ObjectDB.
  137. }
  138. RotatedFileLogger::RotatedFileLogger(const String &p_base_path, int p_max_files) :
  139. base_path(p_base_path.simplify_path()),
  140. max_files(p_max_files > 0 ? p_max_files : 1) {
  141. rotate_file();
  142. #ifdef MODULE_REGEX_ENABLED
  143. strip_ansi_regex.instantiate();
  144. strip_ansi_regex->detach_from_objectdb(); // Note: This RegEx instance will exist longer than ObjectDB, therefore can't be registered in ObjectDB.
  145. strip_ansi_regex->compile("\u001b\\[((?:\\d|;)*)([a-zA-Z])");
  146. #endif // MODULE_REGEX_ENABLED
  147. }
  148. void RotatedFileLogger::logv(const char *p_format, va_list p_list, bool p_err) {
  149. if (!should_log(p_err)) {
  150. return;
  151. }
  152. if (file.is_valid()) {
  153. const int static_buf_size = 512;
  154. char static_buf[static_buf_size];
  155. char *buf = static_buf;
  156. va_list list_copy;
  157. va_copy(list_copy, p_list);
  158. int len = vsnprintf(buf, static_buf_size, p_format, p_list);
  159. if (len >= static_buf_size) {
  160. buf = (char *)Memory::alloc_static(len + 1);
  161. vsnprintf(buf, len + 1, p_format, list_copy);
  162. }
  163. va_end(list_copy);
  164. #ifdef MODULE_REGEX_ENABLED
  165. // Strip ANSI escape codes (such as those inserted by `print_rich()`)
  166. // before writing to file, as text editors cannot display those
  167. // correctly.
  168. file->store_string(strip_ansi_regex->sub(String::utf8(buf), "", true));
  169. #else
  170. file->store_buffer((uint8_t *)buf, len);
  171. #endif // MODULE_REGEX_ENABLED
  172. if (len >= static_buf_size) {
  173. Memory::free_static(buf);
  174. }
  175. if (p_err || _flush_stdout_on_print) {
  176. // Don't always flush when printing stdout to avoid performance
  177. // issues when `print()` is spammed in release builds.
  178. file->flush();
  179. }
  180. }
  181. }
  182. void StdLogger::logv(const char *p_format, va_list p_list, bool p_err) {
  183. if (!should_log(p_err)) {
  184. return;
  185. }
  186. if (p_err) {
  187. vfprintf(stderr, p_format, p_list);
  188. } else {
  189. vprintf(p_format, p_list);
  190. if (_flush_stdout_on_print) {
  191. // Don't always flush when printing stdout to avoid performance
  192. // issues when `print()` is spammed in release builds.
  193. fflush(stdout);
  194. }
  195. }
  196. }
  197. CompositeLogger::CompositeLogger(const Vector<Logger *> &p_loggers) :
  198. loggers(p_loggers) {
  199. }
  200. void CompositeLogger::logv(const char *p_format, va_list p_list, bool p_err) {
  201. if (!should_log(p_err)) {
  202. return;
  203. }
  204. for (int i = 0; i < loggers.size(); ++i) {
  205. va_list list_copy;
  206. va_copy(list_copy, p_list);
  207. loggers[i]->logv(p_format, list_copy, p_err);
  208. va_end(list_copy);
  209. }
  210. }
  211. 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) {
  212. if (!should_log(true)) {
  213. return;
  214. }
  215. for (int i = 0; i < loggers.size(); ++i) {
  216. loggers[i]->log_error(p_function, p_file, p_line, p_code, p_rationale, p_editor_notify, p_type, p_script_backtraces);
  217. }
  218. }
  219. void CompositeLogger::add_logger(Logger *p_logger) {
  220. loggers.push_back(p_logger);
  221. }
  222. CompositeLogger::~CompositeLogger() {
  223. for (int i = 0; i < loggers.size(); ++i) {
  224. memdelete(loggers[i]);
  225. }
  226. }