userver: userver/logging/component.hpp Source File
Loading...
Searching...
No Matches
component.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/logging/component.hpp
4/// @brief @copybrief components::Logging
5
6#include <memory>
7#include <string>
8#include <unordered_map>
9
10#include <userver/components/component_fwd.hpp>
11#include <userver/components/raw_component_base.hpp>
12#include <userver/concurrent/async_event_source.hpp>
13#include <userver/os_signals/component.hpp>
14
15#include <userver/rcu/rcu_map.hpp>
16#include <userver/utils/fast_pimpl.hpp>
17#include <userver/utils/periodic_task.hpp>
18#include <userver/utils/statistics/metrics_storage.hpp>
19#include <userver/utils/statistics/writer.hpp>
20
21#include "logger.hpp"
22
23USERVER_NAMESPACE_BEGIN
24
25namespace logging {
26struct TelemetrySettings;
27}
28
29namespace utils {
30template <typename ValueType>
31class DefaultDict;
32}
33
34namespace logging::impl {
35class TpLogger;
36class TcpSocketSink;
37class TelemetrySettingsStorage;
38} // namespace logging::impl
39
40namespace components {
41
42// clang-format off
43
44/// @ingroup userver_components
45///
46/// @brief %Logging component
47///
48/// Allows to configure the default logger and/or additional loggers for your needs.
49///
50/// ## Static options of components::Logging :
51/// @include{doc} scripts/docs/en/components_schema/core/src/logging/component.md
52///
53/// Options inherited from @ref components::RawComponentBase :
54/// @include{doc} scripts/docs/en/components_schema/core/src/components/impl/component_base.md
55///
56/// `default` logger is the one used for `LOG_*`.
57///
58/// ### Logs output
59/// You can specify where logs are written in the `file_path` option:
60/// - Use <tt>file_path: '\@stdout'</tt> to write your logs to standard output stream;
61/// - Use <tt>file_path: '\@stderr'</tt> to write your logs to standard error stream;
62/// - Use <tt>file_path: '\@null'</tt> to suppress sending of logs;
63/// - Use <tt>file_path: /absolute/path/to/log/file.log</tt> to write your logs to file. Use USR1 signal or @ref server::handlers::OnLogRotate to reopen files after log rotation;
64/// - Use <tt>file_path: 'unix:/absolute/path/to/logs.sock'</tt> to write your logs to unix socket. Socket must be created before the service starts and closed by listener after service is shut down.
65///
66/// For sending logs directly to an otlp (opentelemetry) sink, see @ref opentelemetry.
67///
68/// Customization of log sinks beyond the ones listed above is not supported at the moment.
69///
70/// ### Logs format
71/// You can specify in what format logs are written in the `format` option:
72/// - Use `format: tskv` for traditional optimized userver-flavoured TSKV representation. See @ref utils::encoding::TskvParser for the exact format specification;
73/// - Use `format: ltsv` for the same format, with `:` instead of `=` for key-value separator;
74/// - Use `format: raw` for TSKV logs with timestamp and other default tags stripped, useful for @ref custom_loggers "custom loggers";
75/// - Use `format: json` for JSON logs. @ref logging::JsonString can be used with this format for rich hierarchical log tags;
76/// - Use `format: json_yadeploy` for JSON logs with a slightly different structure.
77///
78/// When sending logs using @ref opentelemetry, logs are written to otlp protobuf messages.
79///
80/// Customization of log formats beyond the ones listed above is not supported at the moment.
81///
82/// ## Static configuration examples:
83///
84/// Writing logs to stderr:
85///
86/// @snippet core/functional_tests/basic_chaos/static_config.yaml logging
87///
88/// Advanced configuration showing options for access logs and a custom opentracing logger:
89///
90/// @snippet core/src/components/common_component_list_test.cpp Sample logging component config
91
92// clang-format on
93
94class Logging final : public RawComponentBase {
95public:
96 /// @ingroup userver_component_names
97 /// @brief The default name of @ref components::Logging component
98 static constexpr std::string_view kName = "logging";
99
100 /// The component constructor
101 Logging(const ComponentConfig&, const ComponentContext&);
102 ~Logging() override;
103
104 /// @brief Returns a logger by its name
105 /// @param name Name of the logger
106 /// @returns Pointer to the Logger instance
107 /// @throws std::runtime_error if logger with this name is not registered
108 logging::LoggerPtr GetLogger(const std::string& name);
109
110 /// @brief Returns a text logger by its name
111 /// @param name Name of the logger
112 /// @returns Pointer to the Logger instance
113 /// @throws std::runtime_error if logger with this name is not registered
114 /// @throws std::runtime_error if logger is not a text logger
115 logging::TextLoggerPtr GetTextLogger(const std::string& name);
116
117 /// @brief Sets a logger
118 /// @param name Name of the logger
119 /// @param logger Logger to set
120 ///
121 /// Captures the initial level and sampling rate and applies the current telemetry policy.
122 /// @throws std::runtime_error if logger is null, the name is already registered, or it is `default`.
123 void SetLogger(const std::string& name, logging::LoggerPtr logger);
124
125 /// Replaces ordinary and external logger policies, resolving each name through
126 /// @ref utils::DefaultDict independently. Applies the stricter settings to existing
127 /// and subsequently registered loggers. Log levels never fall below their initial values.
128 /// @note For use only by @ref components::LoggingConfigurator.
129 /// @throws std::runtime_error for invalid sampling rates, without changing the policies.
131 utils::DefaultDict<logging::TelemetrySettings> settings,
132 utils::DefaultDict<logging::TelemetrySettings> restrictions
133 );
134
135 /// Restores levels and sampling rates captured at logger registration and clears the policies.
136 /// @note For use only by @ref components::LoggingConfigurator.
138
139 /// @brief Returns a logger by its name
140 /// @param name Name of the logger
141 /// @returns Pointer to the Logger instance, or `nullptr` if not registered
142 logging::LoggerPtr GetLoggerOptional(const std::string& name);
143
144 void StartSocketLoggingDebug(const std::optional<logging::Level>& log_level);
145 void StopSocketLoggingDebug(const std::optional<logging::Level>& log_level);
146
147 /// Reopens log files after rotation
149 void TryReopenFiles();
150
151 void WriteStatistics(utils::statistics::Writer& writer) const;
152
153 static yaml_config::Schema GetStaticConfigSchema();
154
155private:
156 void Init(const ComponentConfig&, const ComponentContext&);
157 void Stop() noexcept;
158
159 void FlushLogs();
160
161 engine::TaskProcessor& fs_task_processor_;
162 std::unordered_map<std::string, std::shared_ptr<logging::impl::TpLogger>> loggers_;
163 rcu::RcuMap<std::string, logging::LoggerPtr> extra_loggers_;
164 const std::unique_ptr<logging::impl::TelemetrySettingsStorage> telemetry_settings_;
165 utils::PeriodicTask flush_task_;
166 logging::impl::TcpSocketSink* socket_sink_{nullptr};
167 utils::statistics::MetricsStoragePtr metrics_storage_;
168
169 // Subscriptions must be the last fields.
170 os_signals::Subscriber signal_subscriber_;
171};
172
173template <>
174inline constexpr bool kHasValidate<Logging> = true;
175
176} // namespace components
177
178USERVER_NAMESPACE_END