logger.cpp 8.6 KB

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