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) && !defined(USERVER_LOG_SOURCE_PATH_BASE) &&
11 !defined(USERVER_LOG_BUILD_PATH_BASE)
12
13/// @ingroup userver_universal
14///
15/// @brief Short std::string_view with source path for logging.
16/// @hideinitializer
17// We need user's filename here, not ours
18// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
19#define USERVER_FILEPATH
20 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.substr(0, base.size()) == 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// TODO: consteval
60static constexpr std::string_view CutFilePath(const char* path) noexcept {
61 const std::string_view path_view = path;
62 return path_view.substr(impl::PathBaseSize(path_view));
63}
64
65#undef USERVER_LOG_FILEPATH_STRINGIZE
66#undef USERVER_LOG_FILEPATH_STRINGIZE_AUX
67
68} // namespace logging::impl
69
70// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
71#define USERVER_FILEPATH USERVER_NAMESPACE::logging::impl::CutFilePath(__builtin_FILE())
72
73#endif
74
75USERVER_NAMESPACE_END