userver: userver/logging/log_filepath.hpp Source File
Loading...
Searching...
No Matches
log_filepath.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/logging/log_filepath.hpp
4/// @brief Short source path calculator
5
6#include <string_view>
7
8USERVER_NAMESPACE_BEGIN
9
10#if !defined(USERVER_LOG_PREFIX_PATH_BASE) &&
11 !defined(USERVER_LOG_SOURCE_PATH_BASE) &&
12 !defined(USERVER_LOG_BUILD_PATH_BASE)
13
14/// @ingroup userver_universal
15///
16/// @brief Short std::string_view with source path for logging.
17/// @hideinitializer
18// We need user's filename here, not ours
19// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
20#define USERVER_FILEPATH
21 std::string_view { __builtin_FILE() }
22
23#else
24
25namespace logging::impl {
26
27// I know no other way to wrap a macro value in quotes
28// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
29#define USERVER_LOG_FILEPATH_STRINGIZE_AUX(X) #X
30// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
31#define USERVER_LOG_FILEPATH_STRINGIZE(X) USERVER_LOG_FILEPATH_STRINGIZE_AUX(X)
32
33// May have different macro values for different translation units, hence static
34static constexpr std::size_t PathBaseSize(std::string_view path) noexcept {
35 constexpr std::string_view kSourcePathPrefixes[] = {
36#ifdef USERVER_LOG_PREFIX_PATH_BASE
37 USERVER_LOG_FILEPATH_STRINGIZE(USERVER_LOG_PREFIX_PATH_BASE),
38#endif
39#ifdef USERVER_LOG_SOURCE_PATH_BASE
40 USERVER_LOG_FILEPATH_STRINGIZE(USERVER_LOG_SOURCE_PATH_BASE),
41#endif
42#ifdef USERVER_LOG_BUILD_PATH_BASE
43 USERVER_LOG_FILEPATH_STRINGIZE(USERVER_LOG_BUILD_PATH_BASE),
44#endif
45 };
46
47 for (const std::string_view base : kSourcePathPrefixes) {
48 if (path.substr(0, base.size()) == base) {
49 std::size_t base_size = path.find_first_not_of('/', base.size());
50 if (base_size == std::string_view::npos) {
51 base_size = path.size();
52 }
53
54 return base_size;
55 }
56 }
57 return 0;
58}
59
60// TODO: consteval
61static constexpr std::string_view CutFilePath(const char* path) noexcept {
62 const std::string_view path_view = path;
63 return path_view.substr(impl::PathBaseSize(path_view));
64}
65
66#undef USERVER_LOG_FILEPATH_STRINGIZE
67#undef USERVER_LOG_FILEPATH_STRINGIZE_AUX
68
69} // namespace logging::impl
70
71// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
72#define USERVER_FILEPATH
73 USERVER_NAMESPACE::logging::impl::CutFilePath(__builtin_FILE())
74
75#endif
76
77USERVER_NAMESPACE_END