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