2024-01-18 14:15:19 -05:00
|
|
|
// Copyright 2024 Google LLC
|
2022-12-21 16:36:30 +01:00
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2023-09-18 11:56:55 +02:00
|
|
|
// ANCHOR: solution
|
2022-12-21 16:36:30 +01:00
|
|
|
// ANCHOR: setup
|
2024-01-18 14:15:19 -05:00
|
|
|
pub trait Logger {
|
|
|
|
/// Log a message at the given verbosity level.
|
2024-09-20 14:19:53 -07:00
|
|
|
fn log(&self, verbosity: u8, message: &str);
|
2022-12-21 16:36:30 +01:00
|
|
|
}
|
|
|
|
|
2025-01-15 18:22:48 +08:00
|
|
|
struct StderrLogger;
|
2022-12-21 16:36:30 +01:00
|
|
|
|
2025-01-15 18:22:48 +08:00
|
|
|
impl Logger for StderrLogger {
|
2024-09-20 14:19:53 -07:00
|
|
|
fn log(&self, verbosity: u8, message: &str) {
|
2025-01-15 18:22:48 +08:00
|
|
|
eprintln!("verbosity={verbosity}: {message}");
|
2022-12-21 16:36:30 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-18 14:15:19 -05:00
|
|
|
/// Only log messages up to the given verbosity level.
|
2024-03-11 13:30:38 -07:00
|
|
|
struct VerbosityFilter {
|
2024-01-18 14:15:19 -05:00
|
|
|
max_verbosity: u8,
|
2025-01-15 18:22:48 +08:00
|
|
|
inner: StderrLogger,
|
2022-12-21 16:36:30 +01:00
|
|
|
}
|
2025-01-23 03:40:59 -05:00
|
|
|
// ANCHOR_END: setup
|
2022-12-21 16:36:30 +01:00
|
|
|
|
2024-03-11 13:30:38 -07:00
|
|
|
impl Logger for VerbosityFilter {
|
2024-09-20 14:19:53 -07:00
|
|
|
fn log(&self, verbosity: u8, message: &str) {
|
2024-01-18 14:15:19 -05:00
|
|
|
if verbosity <= self.max_verbosity {
|
|
|
|
self.inner.log(verbosity, message);
|
2022-12-21 16:36:30 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ANCHOR: main
|
|
|
|
fn main() {
|
2025-01-15 18:22:48 +08:00
|
|
|
let logger = VerbosityFilter { max_verbosity: 3, inner: StderrLogger };
|
2024-09-20 14:19:53 -07:00
|
|
|
logger.log(5, "FYI");
|
|
|
|
logger.log(2, "Uhoh");
|
2022-12-21 16:36:30 +01:00
|
|
|
}
|
|
|
|
// ANCHOR_END: main
|