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 <cstddef>
7#include <string_view>
8
9USERVER_NAMESPACE_BEGIN
10
11#if !defined(USERVER_LOG_PREFIX_PATH_BASE) && !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 std::string_view(__builtin_FILE())
21
22#else
23
24namespace logging::impl {
25
26// I know no other way to wrap a macro value in quotes
27// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
28#define USERVER_LOG_FILEPATH_STRINGIZE_AUX(X) #X
29// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
30#define USERVER_LOG_FILEPATH_STRINGIZE(X) USERVER_LOG_FILEPATH_STRINGIZE_AUX(X)
31
32// May have different macro values for different translation units, hence static
33static constexpr std::size_t PathBaseSize(std::string_view path) noexcept {
34 constexpr std::string_view kSourcePathPrefixes[] = {
35#ifdef USERVER_LOG_PREFIX_PATH_BASE
36 USERVER_LOG_FILEPATH_STRINGIZE(USERVER_LOG_PREFIX_PATH_BASE),
37#endif
38#ifdef USERVER_LOG_SOURCE_PATH_BASE
39 USERVER_LOG_FILEPATH_STRINGIZE(USERVER_LOG_SOURCE_PATH_BASE),
40#endif
41#ifdef USERVER_LOG_BUILD_PATH_BASE
42 USERVER_LOG_FILEPATH_STRINGIZE(USERVER_LOG_BUILD_PATH_BASE),
43#endif
44 };
45
46 for (const std::string_view base : kSourcePathPrefixes) {
47 if (path.starts_with(base)) {
48 std::size_t base_size = path.find_first_not_of('/', base.size());
49 if (base_size == std::string_view::npos) {
50 base_size = path.size();
51 }
52
53 return base_size;
54 }
55 }
56 return 0;
57}
58
59// May have different macro values for different translation units, hence static. `consteval` breaks the behavior of
60// utils::SourceLocation.
61static constexpr std::string_view CutFilePath(std::string_view path_view) noexcept {
62 path_view.remove_prefix(impl::PathBaseSize(path_view));
63 return 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 USERVER_NAMESPACE::logging::impl::CutFilePath(__builtin_FILE())
73
74#endif
75
76USERVER_NAMESPACE_END