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
9// TODO remove extra includes.
10#include <fmt/format.h>
11#include <concepts>
12#include <userver/formats/serialize/to.hpp>
13
14USERVER_NAMESPACE_BEGIN
15
16#if !defined(USERVER_LOG_PREFIX_PATH_BASE) && !defined(USERVER_LOG_SOURCE_PATH_BASE) &&
17 !defined(USERVER_LOG_BUILD_PATH_BASE)
18
19/// @ingroup userver_universal
20///
21/// @brief Short `std::string_view` with source path for logging.
22/// @hideinitializer
23// We need user's filename here, not ours
24// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
25#define USERVER_FILEPATH std::string_view(__builtin_FILE())
26
27#else
28
29namespace logging::impl {
30
31// I know no other way to wrap a macro value in quotes
32// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
33#define USERVER_LOG_FILEPATH_STRINGIZE_AUX(X) #X
34// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
35#define USERVER_LOG_FILEPATH_STRINGIZE(X) USERVER_LOG_FILEPATH_STRINGIZE_AUX(X)
36
37// May have different macro values for different translation units, hence static
38static constexpr std::size_t PathBaseSize(std::string_view path) noexcept {
39 constexpr std::string_view kSourcePathPrefixes[] = {
40#ifdef USERVER_LOG_PREFIX_PATH_BASE
41 USERVER_LOG_FILEPATH_STRINGIZE(USERVER_LOG_PREFIX_PATH_BASE),
42#endif
43#ifdef USERVER_LOG_SOURCE_PATH_BASE
44 USERVER_LOG_FILEPATH_STRINGIZE(USERVER_LOG_SOURCE_PATH_BASE),
45#endif
46#ifdef USERVER_LOG_BUILD_PATH_BASE
47 USERVER_LOG_FILEPATH_STRINGIZE(USERVER_LOG_BUILD_PATH_BASE),
48#endif
49 };
50
51 for (const std::string_view base : kSourcePathPrefixes) {
52 if (path.starts_with(base)) {
53 std::size_t base_size = path.find_first_not_of('/', base.size());
54 if (base_size == std::string_view::npos) {
55 base_size = path.size();
56 }
57
58 return base_size;
59 }
60 }
61 return 0;
62}
63
64// May have different macro values for different translation units, hence static. `consteval` breaks the behavior of
65// utils::SourceLocation.
66static constexpr std::string_view CutFilePath(std::string_view path_view) noexcept {
67 path_view.remove_prefix(impl::PathBaseSize(path_view));
68 return path_view;
69}
70
71#undef USERVER_LOG_FILEPATH_STRINGIZE
72#undef USERVER_LOG_FILEPATH_STRINGIZE_AUX
73
74} // namespace logging::impl
75
76// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
77#define USERVER_FILEPATH USERVER_NAMESPACE::logging::impl::CutFilePath(__builtin_FILE())
78
79#endif
80
81USERVER_NAMESPACE_END