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