logger.cpp 8.8 KB

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