-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathlog_params.rs
More file actions
356 lines (316 loc) · 11.8 KB
/
Copy pathlog_params.rs
File metadata and controls
356 lines (316 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
use crate::{rcl_bindings::RCUTILS_LOG_SEVERITY, Clock};
use std::{borrow::Borrow, ffi::CString, time::Duration};
/// These parameters determine the behavior of an instance of logging.
#[derive(Debug, Clone, Copy)]
pub struct LogParams<'a> {
/// The name of the logger
logger_name: LoggerName<'a>,
/// The severity of the logging instance.
severity: LogSeverity,
/// Specify when a log message should be published (See[`LoggingOccurrence`] above)
occurs: LogOccurrence,
/// Specify a publication throttling interval for the message. A value of ZERO (0) indicates that the
/// message should not be throttled. Otherwise, the message will only be published once the specified
/// interval has elapsed. This field is typically used to limit the output from high-frequency messages,
/// e.g. if `log!(logger.throttle(Duration::from_secs(1)), "message");` is called every 10ms, it will
/// nevertheless only be published once per second.
throttle: Duration,
/// Specify a clock to use for throttling. By default this will be [`ThrottleClock::SteadyTime`].
throttle_clock: ThrottleClock<'a>,
/// The log message will only published if the specified expression evaluates to true
only_if: bool,
}
impl<'a> LogParams<'a> {
/// Create a set of default log parameters, given the name of a logger
pub fn new(logger_name: LoggerName<'a>) -> Self {
Self {
logger_name,
severity: Default::default(),
occurs: Default::default(),
throttle: Duration::new(0, 0),
throttle_clock: Default::default(),
only_if: true,
}
}
/// Get the logger name
pub fn get_logger_name(&self) -> &LoggerName<'_> {
&self.logger_name
}
/// Get the severity of the log
pub fn get_severity(&self) -> LogSeverity {
self.severity
}
/// Get the occurrence
pub fn get_occurence(&self) -> LogOccurrence {
self.occurs
}
/// Get the throttle interval duration
pub fn get_throttle(&self) -> Duration {
self.throttle
}
/// Get the throttle clock
pub fn get_throttle_clock(&self) -> ThrottleClock<'a> {
self.throttle_clock
}
/// Get the arbitrary filter set by the user
pub fn get_user_filter(&self) -> bool {
self.only_if
}
}
/// Methods for defining the behavior of a logging instance.
///
/// This trait is implemented by Logger, Node, and anything that a `&str` can be
/// [borrowed][1] from, such as string literals (`"my_str"`), [`String`], or
/// [`Cow<str>`][2].
///
/// [1]: Borrow
/// [2]: std::borrow::Cow
pub trait ToLogParams<'a>: Sized {
/// Convert the object into LogParams with default settings
fn to_log_params(self) -> LogParams<'a>;
/// The logging should only happen once
fn once(self) -> LogParams<'a> {
self.occurs(LogOccurrence::Once)
}
/// The first time the logging happens, we should skip it
fn skip_first(self) -> LogParams<'a> {
self.occurs(LogOccurrence::SkipFirst)
}
/// Set the occurrence behavior of the log instance
fn occurs(self, occurs: LogOccurrence) -> LogParams<'a> {
let mut params = self.to_log_params();
params.occurs = occurs;
params
}
/// Set a throttling interval during which this log will not publish. A value
/// of zero will never block the message from being published, and this is the
/// default behavior.
///
/// A negative duration is not valid, but will be treated as a zero duration.
fn throttle(self, throttle: Duration) -> LogParams<'a> {
let mut params = self.to_log_params();
params.throttle = throttle;
params
}
/// Set the clock that will be used to control [throttling][Self::throttle].
fn throttle_clock(self, clock: ThrottleClock<'a>) -> LogParams<'a> {
let mut params = self.to_log_params();
params.throttle_clock = clock;
params
}
/// The log will not be published if a `false` expression is passed into
/// this function.
///
/// Other factors may prevent the log from being published if a `true` is
/// passed in, such as `ToLogParams::throttle` or `ToLogParams::once`
/// filtering the log.
fn only_if(self, only_if: bool) -> LogParams<'a> {
let mut params = self.to_log_params();
params.only_if = only_if;
params
}
/// Log as a debug message.
fn debug(self) -> LogParams<'a> {
self.severity(LogSeverity::Debug)
}
/// Log as an informative message. This is the default, so you don't
/// generally need to use this.
fn info(self) -> LogParams<'a> {
self.severity(LogSeverity::Info)
}
/// Log as a warning message.
fn warn(self) -> LogParams<'a> {
self.severity(LogSeverity::Warn)
}
/// Log as an error message.
fn error(self) -> LogParams<'a> {
self.severity(LogSeverity::Error)
}
/// Log as a fatal message.
fn fatal(self) -> LogParams<'a> {
self.severity(LogSeverity::Fatal)
}
/// Set the severity for this instance of logging. The default value will be
/// [`LogSeverity::Info`].
fn severity(self, severity: LogSeverity) -> LogParams<'a> {
let mut params = self.to_log_params();
params.severity = severity;
params
}
}
/// This is used to borrow a logger name which might be validated (e.g. came
/// from a [`Logger`][1] struct) or not (e.g. a user-defined `&str`). If an
/// unvalidated logger name is used with one of the logging macros, we will log
/// an error about it, and the original log message will be logged with the
/// default logger.
///
/// [1]: crate::Logger
#[derive(Debug, Clone, Copy)]
pub enum LoggerName<'a> {
/// The logger name is already available as a valid CString
Validated(&'a CString),
/// The logger name has not been validated yet
Unvalidated(&'a str),
}
/// Logging severity.
//
// TODO(@mxgrey): Consider whether this is redundant with RCUTILS_LOG_SEVERITY.
// Perhaps we can customize the output of bindgen to automatically change the name
// of RCUTILS_LOG_SEVERITY to just LogSeverity so it's more idiomatic and then
// export it from the rclrs module.
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum LogSeverity {
/// Use the severity level of the parent logger (or the root logger if the
/// current logger has no parent)
Unset,
/// For messages that are not needed outside of debugging.
Debug,
/// For messages that provide useful information about the state of the
/// application.
Info,
/// For messages that indicate something unusual or unintended might have happened.
Warn,
/// For messages that indicate an error has occurred which may cause the application
/// to misbehave.
Error,
/// For messages that indicate an error has occurred which is so severe that the
/// application should terminate because it cannot recover.
///
/// Using this severity level will not automatically cause the application to
/// terminate, the application developer must decide how to do that on a
/// case-by-case basis.
Fatal,
}
impl LogSeverity {
pub(super) fn as_native(&self) -> RCUTILS_LOG_SEVERITY {
use crate::rcl_bindings::rcl_log_severity_t::*;
match self {
LogSeverity::Unset => RCUTILS_LOG_SEVERITY_UNSET,
LogSeverity::Debug => RCUTILS_LOG_SEVERITY_DEBUG,
LogSeverity::Info => RCUTILS_LOG_SEVERITY_INFO,
LogSeverity::Warn => RCUTILS_LOG_SEVERITY_WARN,
LogSeverity::Error => RCUTILS_LOG_SEVERITY_ERROR,
LogSeverity::Fatal => RCUTILS_LOG_SEVERITY_FATAL,
}
}
}
impl TryFrom<i32> for LogSeverity {
type Error = InvalidLogSeverity;
fn try_from(value: i32) -> Result<Self, InvalidLogSeverity> {
use crate::rcl_bindings::rcl_log_severity_t::*;
Ok(match value {
v if v == RCUTILS_LOG_SEVERITY_UNSET as i32 => LogSeverity::Unset,
v if v == RCUTILS_LOG_SEVERITY_DEBUG as i32 => LogSeverity::Debug,
v if v == RCUTILS_LOG_SEVERITY_INFO as i32 => LogSeverity::Info,
v if v == RCUTILS_LOG_SEVERITY_WARN as i32 => LogSeverity::Warn,
v if v == RCUTILS_LOG_SEVERITY_ERROR as i32 => LogSeverity::Error,
v if v == RCUTILS_LOG_SEVERITY_FATAL as i32 => LogSeverity::Fatal,
_ => return Err(InvalidLogSeverity { value }),
})
}
}
/// The error returned when an integer value does not correspond to a defined
/// [`LogSeverity`] variant.
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidLogSeverity {
/// The offending raw value, as received from rcutils or from a
/// `LoggerLevel` message.
pub value: i32,
}
impl std::fmt::Display for InvalidLogSeverity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Invalid logger severity value {}", self.value)
}
}
impl std::error::Error for InvalidLogSeverity {}
impl Default for LogSeverity {
fn default() -> Self {
Self::Info
}
}
/// Specify when a log message should be published
#[derive(Debug, Clone, Copy)]
pub enum LogOccurrence {
/// Every message will be published if all other conditions are met
All,
/// The message will only be published on the first occurrence (Note: no other conditions apply)
Once,
/// The log message will not be published on the first occurrence, but will be published on
/// each subsequent occurrence (assuming all other conditions are met)
SkipFirst,
}
/// This parameter can specify a type of clock for a logger to use when throttling.
#[derive(Debug, Default, Clone, Copy)]
pub enum ThrottleClock<'a> {
/// Use [`std::time::Instant`] as a clock.
#[default]
SteadyTime,
/// Use [`std::time::SystemTime`] as a clock.
SystemTime,
/// Use some [`Clock`] as a clock.
Clock(&'a Clock),
}
impl Default for LogOccurrence {
fn default() -> Self {
Self::All
}
}
// Anything that we can borrow a string from can be used as if it's a logger and
// turned into LogParams
impl<'a, T: Borrow<str>> ToLogParams<'a> for &'a T {
fn to_log_params(self) -> LogParams<'a> {
LogParams::new(LoggerName::Unvalidated(self.borrow()))
}
}
impl<'a> ToLogParams<'a> for &'a str {
fn to_log_params(self) -> LogParams<'a> {
LogParams::new(LoggerName::Unvalidated(self))
}
}
impl<'a> ToLogParams<'a> for LogParams<'a> {
fn to_log_params(self) -> LogParams<'a> {
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn log_severity_try_from_accepts_all_variants() {
assert_eq!(LogSeverity::try_from(0), Ok(LogSeverity::Unset));
assert_eq!(LogSeverity::try_from(10), Ok(LogSeverity::Debug));
assert_eq!(LogSeverity::try_from(20), Ok(LogSeverity::Info));
assert_eq!(LogSeverity::try_from(30), Ok(LogSeverity::Warn));
assert_eq!(LogSeverity::try_from(40), Ok(LogSeverity::Error));
assert_eq!(LogSeverity::try_from(50), Ok(LogSeverity::Fatal));
}
#[test]
fn log_severity_try_from_rejects_unknown_values() {
assert_eq!(
LogSeverity::try_from(99),
Err(InvalidLogSeverity { value: 99 })
);
assert_eq!(
LogSeverity::try_from(-1),
Err(InvalidLogSeverity { value: -1 })
);
}
#[test]
fn log_severity_try_from_round_trips_through_as_native() {
for severity in [
LogSeverity::Unset,
LogSeverity::Debug,
LogSeverity::Info,
LogSeverity::Warn,
LogSeverity::Error,
LogSeverity::Fatal,
] {
assert_eq!(
LogSeverity::try_from(severity.as_native() as i32),
Ok(severity)
);
}
}
}