servers/http/
dyn_log.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use axum::http::StatusCode;
16use axum::response::IntoResponse;
17use common_telemetry::tracing_subscriber::filter;
18use common_telemetry::{info, RELOAD_HANDLE};
19use snafu::OptionExt;
20
21use crate::error::{InternalSnafu, InvalidParameterSnafu, Result};
22
23#[axum_macros::debug_handler]
24pub async fn dyn_log_handler(level: String) -> Result<impl IntoResponse> {
25    let new_filter = level.parse::<filter::Targets>().map_err(|e| {
26        InvalidParameterSnafu {
27            reason: format!("Invalid filter \"{level}\": {e:?}"),
28        }
29        .build()
30    })?;
31    let mut old_filter = None;
32    RELOAD_HANDLE
33        .get()
34        .context(InternalSnafu {
35            err_msg: "Reload handle not initialized",
36        })?
37        .modify(|filter| {
38            old_filter = Some(filter.clone());
39            *filter = new_filter.clone()
40        })
41        .map_err(|e| {
42            InternalSnafu {
43                err_msg: format!("Fail to modify filter: {e:?}"),
44            }
45            .build()
46        })?;
47    let change_note = format!(
48        "Log Level changed from {} to {}",
49        old_filter.map(|f| f.to_string()).unwrap_or_default(),
50        new_filter
51    );
52    info!("{}", change_note.clone());
53    Ok((StatusCode::OK, change_note))
54}