logger.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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/os/dir_access.h"
  32. #include "core/os/os.h"
  33. #include "core/os/time.h"
  34. #include "core/print_string.h"
  35. #include "core/project_settings.h"
  36. // va_copy was defined in the C99, but not in C++ standards before C++11.
  37. // When you compile C++ without --std=c++<XX> option, compilers still define
  38. // va_copy, otherwise you have to use the internal version (__va_copy).
  39. #if !defined(va_copy)
  40. #if defined(__GNUC__)
  41. #define va_copy(d, s) __va_copy((d), (s))
  42. #else
  43. #define va_copy(d, s) ((d) = (s))
  44. #endif
  45. #endif
  46. #if defined(MINGW_ENABLED) || defined(_MSC_VER)
  47. #define sprintf sprintf_s
  48. #endif
  49. bool Logger::should_log(bool p_err) {
  50. return (!p_err || _print_error_enabled) && (p_err || _print_line_enabled);
  51. }
  52. bool Logger::_flush_stdout_on_print = true;
  53. void Logger::set_flush_stdout_on_print(bool value) {
  54. _flush_stdout_on_print = value;
  55. }
  56. void Logger::log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) {
  57. if (!should_log(true)) {
  58. return;
  59. }
  60. const char *err_type = "ERROR";
  61. switch (p_type) {
  62. case ERR_ERROR:
  63. err_type = "ERROR";
  64. break;
  65. case ERR_WARNING:
  66. err_type = "WARNING";
  67. break;
  68. case ERR_SCRIPT:
  69. err_type = "SCRIPT ERROR";
  70. break;
  71. case ERR_SHADER:
  72. err_type = "SHADER ERROR";
  73. break;
  74. default:
  75. ERR_PRINT("Unknown error type");
  76. break;
  77. }
  78. const char *err_details;
  79. if (p_rationale && *p_rationale) {
  80. err_details = p_rationale;
  81. } else {
  82. err_details = p_code;
  83. }
  84. logf_error("%s: %s\n", err_type, err_details);
  85. logf_error(" at: %s (%s:%i) - %s\n", p_function, p_file, p_line, p_code);
  86. }
  87. void Logger::logf(const char *p_format, ...) {
  88. if (!should_log(false)) {
  89. return;
  90. }
  91. va_list argp;
  92. va_start(argp, p_format);
  93. logv(p_format, argp, false);
  94. va_end(argp);
  95. }
  96. void Logger::logf_error(const char *p_format, ...) {
  97. if (!should_log(true)) {
  98. return;
  99. }
  100. va_list argp;
  101. va_start(argp, p_format);
  102. logv(p_format, argp, true);
  103. va_end(argp);
  104. }
  105. Logger::~Logger() {}
  106. void RotatedFileLogger::close_file() {
  107. if (file) {
  108. memdelete(file);
  109. file = nullptr;
  110. }
  111. }
  112. void RotatedFileLogger::clear_old_backups() {
  113. int max_backups = max_files - 1; // -1 for the current file
  114. String basename = base_path.get_file().get_basename();
  115. String extension = base_path.get_extension();
  116. DirAccess *da = DirAccess::open(base_path.get_base_dir());
  117. if (!da) {
  118. return;
  119. }
  120. da->list_dir_begin();
  121. String f = da->get_next();
  122. Set<String> backups;
  123. while (f != String()) {
  124. if (!da->current_is_dir() && f.begins_with(basename) && f.get_extension() == extension && f != base_path.get_file()) {
  125. backups.insert(f);
  126. }
  127. f = da->get_next();
  128. }
  129. da->list_dir_end();
  130. if (backups.size() > max_backups) {
  131. // since backups are appended with timestamp and Set iterates them in sorted order,
  132. // first backups are the oldest
  133. int to_delete = backups.size() - max_backups;
  134. for (Set<String>::Element *E = backups.front(); E && to_delete > 0; E = E->next(), --to_delete) {
  135. da->remove(E->get());
  136. }
  137. }
  138. memdelete(da);
  139. }
  140. void RotatedFileLogger::rotate_file() {
  141. close_file();
  142. if (FileAccess::exists(base_path)) {
  143. if (max_files > 1) {
  144. String timestamp = Time::get_singleton()->get_datetime_string_from_system().replace(":", ".");
  145. String backup_name = base_path.get_basename() + timestamp;
  146. if (base_path.get_extension() != String()) {
  147. backup_name += "." + base_path.get_extension();
  148. }
  149. DirAccess *da = DirAccess::open(base_path.get_base_dir());
  150. if (da) {
  151. da->copy(base_path, backup_name);
  152. memdelete(da);
  153. }
  154. clear_old_backups();
  155. }
  156. } else {
  157. DirAccess *da = DirAccess::create(DirAccess::ACCESS_USERDATA);
  158. if (da) {
  159. da->make_dir_recursive(base_path.get_base_dir());
  160. memdelete(da);
  161. }
  162. }
  163. file = FileAccess::open(base_path, FileAccess::WRITE);
  164. }
  165. RotatedFileLogger::RotatedFileLogger(const String &p_base_path, int p_max_files) :
  166. base_path(p_base_path.simplify_path()),
  167. max_files(p_max_files > 0 ? p_max_files : 1),
  168. file(nullptr) {
  169. rotate_file();
  170. }
  171. void RotatedFileLogger::logv(const char *p_format, va_list p_list, bool p_err) {
  172. if (!should_log(p_err)) {
  173. return;
  174. }
  175. if (file) {
  176. const int static_buf_size = 512;
  177. char static_buf[static_buf_size];
  178. char *buf = static_buf;
  179. va_list list_copy;
  180. va_copy(list_copy, p_list);
  181. int len = vsnprintf(buf, static_buf_size, p_format, p_list);
  182. if (len >= static_buf_size) {
  183. buf = (char *)Memory::alloc_static(len + 1);
  184. vsnprintf(buf, len + 1, p_format, list_copy);
  185. }
  186. va_end(list_copy);
  187. file->store_buffer((uint8_t *)buf, len);
  188. if (len >= static_buf_size) {
  189. Memory::free_static(buf);
  190. }
  191. if (p_err || _flush_stdout_on_print) {
  192. // Don't always flush when printing stdout to avoid performance
  193. // issues when `print()` is spammed in release builds.
  194. file->flush();
  195. }
  196. }
  197. }
  198. RotatedFileLogger::~RotatedFileLogger() {
  199. close_file();
  200. }
  201. void StdLogger::logv(const char *p_format, va_list p_list, bool p_err) {
  202. if (!should_log(p_err)) {
  203. return;
  204. }
  205. if (p_err) {
  206. vfprintf(stderr, p_format, p_list);
  207. } else {
  208. vprintf(p_format, p_list);
  209. if (_flush_stdout_on_print) {
  210. // Don't always flush when printing stdout to avoid performance
  211. // issues when `print()` is spammed in release builds.
  212. fflush(stdout);
  213. }
  214. }
  215. }
  216. StdLogger::~StdLogger() {}
  217. CompositeLogger::CompositeLogger(Vector<Logger *> p_loggers) :
  218. loggers(p_loggers) {
  219. }
  220. void CompositeLogger::logv(const char *p_format, va_list p_list, bool p_err) {
  221. if (!should_log(p_err)) {
  222. return;
  223. }
  224. for (int i = 0; i < loggers.size(); ++i) {
  225. va_list list_copy;
  226. va_copy(list_copy, p_list);
  227. loggers[i]->logv(p_format, list_copy, p_err);
  228. va_end(list_copy);
  229. }
  230. }
  231. void CompositeLogger::log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) {
  232. if (!should_log(true)) {
  233. return;
  234. }
  235. for (int i = 0; i < loggers.size(); ++i) {
  236. loggers[i]->log_error(p_function, p_file, p_line, p_code, p_rationale, p_type);
  237. }
  238. }
  239. void CompositeLogger::add_logger(Logger *p_logger) {
  240. loggers.push_back(p_logger);
  241. }
  242. CompositeLogger::~CompositeLogger() {
  243. for (int i = 0; i < loggers.size(); ++i) {
  244. memdelete(loggers[i]);
  245. }
  246. }