Strip ANSI escape codes from file logging
Text editors cannot display ANSI escape codes, so these should be stripped from log files to ensure readability. Since this uses a regex, this works both for `print_rich()` and manually inserted ANSI escape codes. Co-authored-by: bruvzg <7645683+bruvzg@users.noreply.github.com>
This commit is contained in:
parent
c7f56d327d
commit
459f14c098
|
@ -37,6 +37,8 @@
|
|||
#include "core/os/time.h"
|
||||
#include "core/string/print_string.h"
|
||||
|
||||
#include "modules/modules_enabled.gen.h" // For regex.
|
||||
|
||||
#if defined(MINGW_ENABLED) || defined(_MSC_VER)
|
||||
#define sprintf sprintf_s
|
||||
#endif
|
||||
|
@ -180,6 +182,12 @@ RotatedFileLogger::RotatedFileLogger(const String &p_base_path, int p_max_files)
|
|||
base_path(p_base_path.simplify_path()),
|
||||
max_files(p_max_files > 0 ? p_max_files : 1) {
|
||||
rotate_file();
|
||||
|
||||
#ifdef MODULE_REGEX_ENABLED
|
||||
strip_ansi_regex.instantiate();
|
||||
strip_ansi_regex->detach_from_objectdb(); // Note: This RegEx instance will exist longer than ObjectDB, therefore can't be registered in ObjectDB.
|
||||
strip_ansi_regex->compile("\u001b\\[((?:\\d|;)*)([a-zA-Z])");
|
||||
#endif // MODULE_REGEX_ENABLED
|
||||
}
|
||||
|
||||
void RotatedFileLogger::logv(const char *p_format, va_list p_list, bool p_err) {
|
||||
|
@ -199,7 +207,15 @@ void RotatedFileLogger::logv(const char *p_format, va_list p_list, bool p_err) {
|
|||
vsnprintf(buf, len + 1, p_format, list_copy);
|
||||
}
|
||||
va_end(list_copy);
|
||||
|
||||
#ifdef MODULE_REGEX_ENABLED
|
||||
// Strip ANSI escape codes (such as those inserted by `print_rich()`)
|
||||
// before writing to file, as text editors cannot display those
|
||||
// correctly.
|
||||
file->store_string(strip_ansi_regex->sub(String(buf), "", true));
|
||||
#else
|
||||
file->store_buffer((uint8_t *)buf, len);
|
||||
#endif // MODULE_REGEX_ENABLED
|
||||
|
||||
if (len >= static_buf_size) {
|
||||
Memory::free_static(buf);
|
||||
|
|
|
@ -34,6 +34,10 @@
|
|||
#include "core/io/file_access.h"
|
||||
#include "core/string/ustring.h"
|
||||
#include "core/templates/vector.h"
|
||||
#include "modules/modules_enabled.gen.h" // For regex.
|
||||
#ifdef MODULE_REGEX_ENABLED
|
||||
#include "modules/regex/regex.h"
|
||||
#endif // MODULE_REGEX_ENABLED
|
||||
|
||||
#include <stdarg.h>
|
||||
|
||||
|
@ -86,6 +90,10 @@ class RotatedFileLogger : public Logger {
|
|||
void clear_old_backups();
|
||||
void rotate_file();
|
||||
|
||||
#ifdef MODULE_REGEX_ENABLED
|
||||
Ref<RegEx> strip_ansi_regex;
|
||||
#endif // MODULE_REGEX_ENABLED
|
||||
|
||||
public:
|
||||
explicit RotatedFileLogger(const String &p_base_path, int p_max_files = 10);
|
||||
|
||||
|
|
Loading…
Reference in New Issue