logger.cpp 8.6 KB

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