logger.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /*************************************************************************/
  2. /* logger.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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. }
  83. logf_error("%s: %s\n", err_type, err_details);
  84. logf_error(" at: %s (%s:%i) - %s\n", p_function, p_file, p_line, p_code);
  85. }
  86. void Logger::logf(const char *p_format, ...) {
  87. if (!should_log(false)) {
  88. return;
  89. }
  90. va_list argp;
  91. va_start(argp, p_format);
  92. logv(p_format, argp, false);
  93. va_end(argp);
  94. }
  95. void Logger::logf_error(const char *p_format, ...) {
  96. if (!should_log(true)) {
  97. return;
  98. }
  99. va_list argp;
  100. va_start(argp, p_format);
  101. logv(p_format, argp, true);
  102. va_end(argp);
  103. }
  104. Logger::~Logger() {}
  105. void RotatedFileLogger::close_file() {
  106. if (file) {
  107. memdelete(file);
  108. file = nullptr;
  109. }
  110. }
  111. void RotatedFileLogger::clear_old_backups() {
  112. int max_backups = max_files - 1; // -1 for the current file
  113. String basename = base_path.get_file().get_basename();
  114. String extension = base_path.get_extension();
  115. DirAccess *da = DirAccess::open(base_path.get_base_dir());
  116. if (!da) {
  117. return;
  118. }
  119. da->list_dir_begin();
  120. String f = da->get_next();
  121. Set<String> backups;
  122. while (f != String()) {
  123. if (!da->current_is_dir() && f.begins_with(basename) && f.get_extension() == extension && f != base_path.get_file()) {
  124. backups.insert(f);
  125. }
  126. f = da->get_next();
  127. }
  128. da->list_dir_end();
  129. if (backups.size() > max_backups) {
  130. // since backups are appended with timestamp and Set iterates them in sorted order,
  131. // first backups are the oldest
  132. int to_delete = backups.size() - max_backups;
  133. for (Set<String>::Element *E = backups.front(); E && to_delete > 0; E = E->next(), --to_delete) {
  134. da->remove(E->get());
  135. }
  136. }
  137. memdelete(da);
  138. }
  139. void RotatedFileLogger::rotate_file() {
  140. close_file();
  141. if (FileAccess::exists(base_path)) {
  142. if (max_files > 1) {
  143. const size_t TIMESTAMP_SIZE = 21;
  144. char timestamp[TIMESTAMP_SIZE];
  145. OS::Date date = OS::get_singleton()->get_date();
  146. OS::Time time = OS::get_singleton()->get_time();
  147. snprintf(timestamp, TIMESTAMP_SIZE, "_%04d-%02d-%02d_%02d.%02d.%02d", date.year, date.month, date.day, time.hour, time.min, time.sec);
  148. String backup_name = base_path.get_basename() + timestamp;
  149. if (base_path.get_extension() != String()) {
  150. backup_name += "." + base_path.get_extension();
  151. }
  152. DirAccess *da = DirAccess::open(base_path.get_base_dir());
  153. if (da) {
  154. da->copy(base_path, backup_name);
  155. memdelete(da);
  156. }
  157. clear_old_backups();
  158. }
  159. } else {
  160. DirAccess *da = DirAccess::create(DirAccess::ACCESS_USERDATA);
  161. if (da) {
  162. da->make_dir_recursive(base_path.get_base_dir());
  163. memdelete(da);
  164. }
  165. }
  166. file = FileAccess::open(base_path, FileAccess::WRITE);
  167. }
  168. RotatedFileLogger::RotatedFileLogger(const String &p_base_path, int p_max_files) :
  169. base_path(p_base_path.simplify_path()),
  170. max_files(p_max_files > 0 ? p_max_files : 1),
  171. file(nullptr) {
  172. rotate_file();
  173. }
  174. void RotatedFileLogger::logv(const char *p_format, va_list p_list, bool p_err) {
  175. if (!should_log(p_err)) {
  176. return;
  177. }
  178. if (file) {
  179. const int static_buf_size = 512;
  180. char static_buf[static_buf_size];
  181. char *buf = static_buf;
  182. va_list list_copy;
  183. va_copy(list_copy, p_list);
  184. int len = vsnprintf(buf, static_buf_size, p_format, p_list);
  185. if (len >= static_buf_size) {
  186. buf = (char *)Memory::alloc_static(len + 1);
  187. vsnprintf(buf, len + 1, p_format, list_copy);
  188. }
  189. va_end(list_copy);
  190. file->store_buffer((uint8_t *)buf, len);
  191. if (len >= static_buf_size) {
  192. Memory::free_static(buf);
  193. }
  194. if (p_err || _flush_stdout_on_print) {
  195. // Don't always flush when printing stdout to avoid performance
  196. // issues when `print()` is spammed in release builds.
  197. file->flush();
  198. }
  199. }
  200. }
  201. RotatedFileLogger::~RotatedFileLogger() {
  202. close_file();
  203. }
  204. void StdLogger::logv(const char *p_format, va_list p_list, bool p_err) {
  205. if (!should_log(p_err)) {
  206. return;
  207. }
  208. if (p_err) {
  209. vfprintf(stderr, p_format, p_list);
  210. } else {
  211. vprintf(p_format, p_list);
  212. if (_flush_stdout_on_print) {
  213. // Don't always flush when printing stdout to avoid performance
  214. // issues when `print()` is spammed in release builds.
  215. fflush(stdout);
  216. }
  217. }
  218. }
  219. StdLogger::~StdLogger() {}
  220. CompositeLogger::CompositeLogger(Vector<Logger *> p_loggers) :
  221. loggers(p_loggers) {
  222. }
  223. void CompositeLogger::logv(const char *p_format, va_list p_list, bool p_err) {
  224. if (!should_log(p_err)) {
  225. return;
  226. }
  227. for (int i = 0; i < loggers.size(); ++i) {
  228. va_list list_copy;
  229. va_copy(list_copy, p_list);
  230. loggers[i]->logv(p_format, list_copy, p_err);
  231. va_end(list_copy);
  232. }
  233. }
  234. 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) {
  235. if (!should_log(true)) {
  236. return;
  237. }
  238. for (int i = 0; i < loggers.size(); ++i) {
  239. loggers[i]->log_error(p_function, p_file, p_line, p_code, p_rationale, p_type);
  240. }
  241. }
  242. void CompositeLogger::add_logger(Logger *p_logger) {
  243. loggers.push_back(p_logger);
  244. }
  245. CompositeLogger::~CompositeLogger() {
  246. for (int i = 0; i < loggers.size(); ++i) {
  247. memdelete(loggers[i]);
  248. }
  249. }