logger.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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: err_type = "**ERROR**"; break;
  62. case ERR_WARNING: err_type = "**WARNING**"; break;
  63. case ERR_SCRIPT: err_type = "**SCRIPT ERROR**"; break;
  64. case ERR_SHADER: err_type = "**SHADER ERROR**"; break;
  65. default: ERR_PRINT("Unknown error type"); break;
  66. }
  67. const char *err_details;
  68. if (p_rationale && *p_rationale)
  69. err_details = p_rationale;
  70. else
  71. err_details = p_code;
  72. logf_error("%s: %s\n", err_type, err_details);
  73. logf_error(" At: %s:%i:%s() - %s\n", p_file, p_line, p_function, p_code);
  74. }
  75. void Logger::logf(const char *p_format, ...) {
  76. if (!should_log(false)) {
  77. return;
  78. }
  79. va_list argp;
  80. va_start(argp, p_format);
  81. logv(p_format, argp, false);
  82. va_end(argp);
  83. }
  84. void Logger::logf_error(const char *p_format, ...) {
  85. if (!should_log(true)) {
  86. return;
  87. }
  88. va_list argp;
  89. va_start(argp, p_format);
  90. logv(p_format, argp, true);
  91. va_end(argp);
  92. }
  93. Logger::~Logger() {}
  94. void RotatedFileLogger::close_file() {
  95. if (file) {
  96. memdelete(file);
  97. file = NULL;
  98. }
  99. }
  100. void RotatedFileLogger::clear_old_backups() {
  101. int max_backups = max_files - 1; // -1 for the current file
  102. String basename = base_path.get_file().get_basename();
  103. String extension = base_path.get_extension();
  104. DirAccess *da = DirAccess::open(base_path.get_base_dir());
  105. if (!da) {
  106. return;
  107. }
  108. da->list_dir_begin();
  109. String f = da->get_next();
  110. Set<String> backups;
  111. while (f != String()) {
  112. if (!da->current_is_dir() && f.begins_with(basename) && f.get_extension() == extension && f != base_path.get_file()) {
  113. backups.insert(f);
  114. }
  115. f = da->get_next();
  116. }
  117. da->list_dir_end();
  118. if (backups.size() > max_backups) {
  119. // since backups are appended with timestamp and Set iterates them in sorted order,
  120. // first backups are the oldest
  121. int to_delete = backups.size() - max_backups;
  122. for (Set<String>::Element *E = backups.front(); E && to_delete > 0; E = E->next(), --to_delete) {
  123. da->remove(E->get());
  124. }
  125. }
  126. memdelete(da);
  127. }
  128. void RotatedFileLogger::rotate_file() {
  129. close_file();
  130. if (FileAccess::exists(base_path)) {
  131. if (max_files > 1) {
  132. const size_t TIMESTAMP_SIZE = 21;
  133. char timestamp[TIMESTAMP_SIZE];
  134. OS::Date date = OS::get_singleton()->get_date();
  135. OS::Time time = OS::get_singleton()->get_time();
  136. snprintf(timestamp, TIMESTAMP_SIZE, "_%04d-%02d-%02d_%02d.%02d.%02d", date.year, date.month, date.day, time.hour, time.min, time.sec);
  137. String backup_name = base_path.get_basename() + timestamp;
  138. if (base_path.get_extension() != String()) {
  139. backup_name += "." + base_path.get_extension();
  140. }
  141. DirAccess *da = DirAccess::open(base_path.get_base_dir());
  142. if (da) {
  143. da->copy(base_path, backup_name);
  144. memdelete(da);
  145. }
  146. clear_old_backups();
  147. }
  148. } else {
  149. DirAccess *da = DirAccess::create(DirAccess::ACCESS_USERDATA);
  150. if (da) {
  151. da->make_dir_recursive(base_path.get_base_dir());
  152. memdelete(da);
  153. }
  154. }
  155. file = FileAccess::open(base_path, FileAccess::WRITE);
  156. }
  157. RotatedFileLogger::RotatedFileLogger(const String &p_base_path, int p_max_files) :
  158. base_path(p_base_path.simplify_path()),
  159. max_files(p_max_files > 0 ? p_max_files : 1),
  160. file(NULL) {
  161. rotate_file();
  162. }
  163. void RotatedFileLogger::logv(const char *p_format, va_list p_list, bool p_err) {
  164. if (!should_log(p_err)) {
  165. return;
  166. }
  167. if (file) {
  168. const int static_buf_size = 512;
  169. char static_buf[static_buf_size];
  170. char *buf = static_buf;
  171. va_list list_copy;
  172. va_copy(list_copy, p_list);
  173. int len = vsnprintf(buf, static_buf_size, p_format, p_list);
  174. if (len >= static_buf_size) {
  175. buf = (char *)Memory::alloc_static(len + 1);
  176. vsnprintf(buf, len + 1, p_format, list_copy);
  177. }
  178. va_end(list_copy);
  179. file->store_buffer((uint8_t *)buf, len);
  180. if (len >= static_buf_size) {
  181. Memory::free_static(buf);
  182. }
  183. if (p_err || _flush_stdout_on_print) {
  184. // Don't always flush when printing stdout to avoid performance
  185. // issues when `print()` is spammed in release builds.
  186. file->flush();
  187. }
  188. }
  189. }
  190. RotatedFileLogger::~RotatedFileLogger() {
  191. close_file();
  192. }
  193. void StdLogger::logv(const char *p_format, va_list p_list, bool p_err) {
  194. if (!should_log(p_err)) {
  195. return;
  196. }
  197. if (p_err) {
  198. vfprintf(stderr, p_format, p_list);
  199. } else {
  200. vprintf(p_format, p_list);
  201. if (_flush_stdout_on_print) {
  202. // Don't always flush when printing stdout to avoid performance
  203. // issues when `print()` is spammed in release builds.
  204. fflush(stdout);
  205. }
  206. }
  207. }
  208. StdLogger::~StdLogger() {}
  209. CompositeLogger::CompositeLogger(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, 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_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. }