logger.cpp 8.4 KB

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