From 6390c66e950b0536c438bf3be1ea78fd0540d6c9 Mon Sep 17 00:00:00 2001 From: Yuri Kunde Schlesner Date: Tue, 4 Nov 2014 03:03:19 -0200 Subject: Implement text path trimming for shorter paths. --- src/common/logging/text_formatter.cpp | 27 ++++++++++++++++++++++++++- src/common/logging/text_formatter.h | 12 ++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) (limited to 'src/common/logging') diff --git a/src/common/logging/text_formatter.cpp b/src/common/logging/text_formatter.cpp index b603ead1..88deb150 100644 --- a/src/common/logging/text_formatter.cpp +++ b/src/common/logging/text_formatter.cpp @@ -14,8 +14,33 @@ #include "common/logging/log.h" #include "common/logging/text_formatter.h" +#include "common/string_util.h" + namespace Log { +// TODO(bunnei): This should be moved to a generic path manipulation library +const char* TrimSourcePath(const char* path, const char* root) { + const char* p = path; + + while (*p != '\0') { + const char* next_slash = p; + while (*next_slash != '\0' && *next_slash != '/' && *next_slash != '\\') { + ++next_slash; + } + + bool is_src = Common::ComparePartialString(p, next_slash, root); + p = next_slash; + + if (*p != '\0') { + ++p; + } + if (is_src) { + path = p; + } + } + return path; +} + void FormatLogMessage(const Entry& entry, char* out_text, size_t text_len) { unsigned int time_seconds = static_cast(entry.timestamp.count() / 1000000); unsigned int time_fractional = static_cast(entry.timestamp.count() % 1000000); @@ -25,7 +50,7 @@ void FormatLogMessage(const Entry& entry, char* out_text, size_t text_len) { snprintf(out_text, text_len, "[%4u.%06u] %s <%s> %s: %s", time_seconds, time_fractional, class_name, level_name, - entry.location.c_str(), entry.message.c_str()); + TrimSourcePath(entry.location.c_str()), entry.message.c_str()); } static void ChangeConsoleColor(Level level) { diff --git a/src/common/logging/text_formatter.h b/src/common/logging/text_formatter.h index 6c2a6f1e..04164600 100644 --- a/src/common/logging/text_formatter.h +++ b/src/common/logging/text_formatter.h @@ -12,6 +12,18 @@ namespace Log { class Logger; struct Entry; +/** + * Attempts to trim an arbitrary prefix from `path`, leaving only the part starting at `root`. It's + * intended to be used to strip a system-specific build directory from the `__FILE__` macro, + * leaving only the path relative to the sources root. + * + * @param path The input file path as a null-terminated string + * @param root The name of the root source directory as a null-terminated string. Path up to and + * including the last occurence of this name will be stripped + * @return A pointer to the same string passed as `path`, but starting at the trimmed portion + */ +const char* TrimSourcePath(const char* path, const char* root = "src"); + /// Formats a log entry into the provided text buffer. void FormatLogMessage(const Entry& entry, char* out_text, size_t text_len); /// Formats and prints a log entry to stderr. -- cgit v1.2.3