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 <userver/utils/string_literal.hpp>
7#include <userver/utils/zstring_view.hpp>
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 @ref utils::zstring_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 USERVER_NAMESPACE::utils::zstring_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(utils::zstring_view path) noexcept {
35 constexpr utils::StringLiteral 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 utils::StringLiteral 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// May have different macro values for different translation units, hence static. `consteval` breaks the behavior of
61// utils::SourceLocation.
62static constexpr utils::zstring_view CutFilePath(utils::zstring_view path_view) noexcept {
63 path_view.remove_prefix(impl::PathBaseSize(path_view));
64 return path_view;
65}
66
67#undef USERVER_LOG_FILEPATH_STRINGIZE
68#undef USERVER_LOG_FILEPATH_STRINGIZE_AUX
69
70} // namespace logging::impl
71
72// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
73#define USERVER_FILEPATH USERVER_NAMESPACE::logging::impl::CutFilePath(__builtin_FILE())
74
75#endif
76
77USERVER_NAMESPACE_END