Factor out instrumentation code. Add metrics and logging to otel.

This commit is contained in:
Daniel Lundin 2024-11-27 16:31:04 +01:00
commit 2da3a239cd
Signed by: dln
SSH key fingerprint: SHA256:dQy1Xj3UiqJYpKR5ggQ2bxgz4jCH8IF+k3AB8o0kmdI
6 changed files with 200 additions and 50 deletions
controller/src/bin

View file

@ -0,0 +1,102 @@
use anyhow::{anyhow, Result};
use clap::Parser;
use dropshot::{
endpoint, ApiDescription, ConfigDropshot, HttpError, HttpResponseOk, RequestContext,
ServerBuilder,
};
use schemars::JsonSchema;
use serde::Serialize;
use slog::Drain;
use tracing_slog::TracingSlogDrain;
use std::net::SocketAddr;
use std::str::FromStr;
use std::sync::Arc;
use patagia_controller::instrumentation;
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Cli {}
/// Represents a project in our API.
#[derive(Serialize, JsonSchema)]
struct VersionInfo {
name: String,
version: String,
}
/// Fetch version info.
#[endpoint {
method = GET,
path = "/version",
}]
#[tracing::instrument(
skip(rqctx),
fields(
http.method=rqctx.request.method().as_str(),
http.path=rqctx.request.uri().path(),
http.remote_ip=rqctx.request.remote_addr().ip().to_string(),
request_id = rqctx.request_id,
),
err(Debug),
)]
async fn api_version(
rqctx: RequestContext<Arc<()>>,
) -> Result<HttpResponseOk<VersionInfo>, HttpError> {
let ver = VersionInfo {
name: env!("CARGO_PKG_NAME").to_string(),
version: env!("CARGO_PKG_VERSION").to_string(),
};
tracing::info!("Someone made a request to /version");
Ok(HttpResponseOk(ver))
}
#[tokio::main]
async fn main() -> Result<()> {
let _args = Cli::parse();
let _tracing = instrumentation::init_tracing_subscriber()?;
tracing::info!("Patagia Controller");
tracing::debug!("Starting server");
tracing::error!(name: "my-event-name", target: "my-system", event_id = 20, user_name = "otel", user_email = "otel@opentelemetry.io", message = "This is an example message");
foo().await;
let mut api = ApiDescription::new();
api.register(api_version).unwrap();
let config = ConfigDropshot {
bind_address: SocketAddr::from_str("0.0.0.0:9474").unwrap(),
..Default::default()
};
// Adapt the Dropshot logger to tracing
let logger = {
let level_drain = slog::LevelFilter(TracingSlogDrain, slog::Level::Debug).fuse();
let async_drain = slog_async::Async::new(level_drain).build().fuse();
slog::Logger::root(async_drain, slog::o!())
};
ServerBuilder::new(api, Arc::new(()), logger)
.config(config)
.start()
.map_err(|e| anyhow!("Error starting server: {:?}", e))?
.await
.map_err(|e| anyhow!(e))
}
#[tracing::instrument]
async fn foo() {
tracing::info!(
monotonic_counter.foo = 1_u64,
key_1 = "bar",
key_2 = 10,
"handle foo",
);
tracing::info!(histogram.baz = 10, "histogram example",);
}