Skip to content

Commit

Permalink
style(logging): improve logged output
Browse files Browse the repository at this point in the history
  • Loading branch information
the-wondersmith committed Jun 11, 2023
1 parent cf7a12d commit 10366f4
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 19 deletions.
4 changes: 2 additions & 2 deletions cog.toml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# [Cocogitto](https://docs.cocogitto.io/) Configuration

tag_prefix = "v"
from_latest_tag = false
ignore_merge_commits = false
ignore_merge_commits = true
branch_whitelist = [ "main", "release/**" ]
pre_bump_hooks = [
"cargo build --release",
"cargo doc",
"echo 'bumping from {{latest}} to {{version}}'",
"cargo bump {{version}}",
]
Expand Down
39 changes: 22 additions & 17 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@ use std::{collections::HashMap, env, fmt::Debug, net::SocketAddr};
// Third Party Imports
use axum::{
body::Bytes,
extract::{Json, Path, Query},
extract::{ConnectInfo, Json, Path, Query},
http::{HeaderMap, Method},
middleware, routing, Router,
};

pub(crate) mod metrics;

#[derive(Debug, serde::Serialize, Clone)]
#[derive(Clone, Debug, serde::Serialize)]
struct Echo {
client: String,
method: String,
path: String,
headers: HashMap<String, String>,
Expand All @@ -28,6 +29,8 @@ struct Echo {
#[derive(Debug, clap::Parser)]
#[command(author, version, about)]
struct Args {
#[arg(short = 'h', long = "host", env = "ECHO_HOST", default_value = "[::]")]
pub host: String,
#[arg(short = 'p', long = "port", env = "ECHO_PORT", default_value_t = 8080)]
pub port: usize,
#[arg(
Expand All @@ -52,8 +55,9 @@ struct Args {
pub log_level: tracing::Level,
}

#[tracing::instrument]
#[tracing::instrument(ret, skip_all, parent = None)]
async fn serialize_request(
ConnectInfo(client): ConnectInfo<SocketAddr>,
method: Method,
path: Option<Path<String>>,
Query(params): Query<HashMap<String, String>>,
Expand Down Expand Up @@ -90,11 +94,10 @@ async fn serialize_request(
})
};

let method = method.to_string();

tracing::info!("{} {}", &method, &path);
let (client, method) = (client.to_string(), method.to_string());

Json(Echo {
client,
method,
path,
headers,
Expand Down Expand Up @@ -130,26 +133,26 @@ async fn echo_router() -> anyhow::Result<Router> {
.route_layer(middleware::from_fn(metrics::track_metrics)))
}

#[tracing::instrument]
async fn serve_app(port: usize) -> anyhow::Result<()> {
#[tracing::instrument(skip_all)]
async fn serve_app(host: &str, port: usize) -> anyhow::Result<()> {
let app = echo_router().await?;

let addr: SocketAddr = format!("[::]:{port}").parse()?;
let addr: SocketAddr = format!("{host}:{port}").parse()?;

tracing::info!("`echo-rs` server listening at: http://{addr}");

axum::Server::bind(&addr)
.serve(app.into_make_service())
.serve(app.into_make_service_with_connect_info::<SocketAddr>())
.await?;

Ok(())
}

#[tracing::instrument]
async fn serve_metrics(port: usize) -> anyhow::Result<()> {
#[tracing::instrument(skip_all)]
async fn serve_metrics(host: &str, port: usize) -> anyhow::Result<()> {
let app = metrics::router();

let addr: SocketAddr = format!("[::]:{port}").parse()?;
let addr: SocketAddr = format!("{host}:{port}").parse()?;

tracing::info!("Serving Prometheus metrics at: http://{addr}");

Expand All @@ -161,8 +164,8 @@ async fn serve_metrics(port: usize) -> anyhow::Result<()> {
Ok(())
}

#[tokio::main]
#[tracing::instrument]
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args = <Args as clap::Parser>::parse();

Expand All @@ -188,10 +191,12 @@ async fn main() -> anyhow::Result<()> {
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");

if !args.metrics {
serve_app(args.port).await
serve_app(&args.host, args.port).await
} else {
let (echo_server, metrics_server) =
tokio::join!(serve_app(args.port), serve_metrics(args.metrics_port));
let (echo_server, metrics_server) = tokio::join!(
serve_app(&args.host, args.port),
serve_metrics(&args.host, args.metrics_port)
);
let (_, _) = (echo_server?, metrics_server?);

Ok(())
Expand Down
4 changes: 4 additions & 0 deletions src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use axum::{
};
use metrics_exporter_prometheus::{Matcher, PrometheusBuilder, PrometheusHandle};

#[tracing::instrument]
pub(crate) fn router() -> Router {
let recorder_handle = setup_metrics_recorder();
Router::new().route(
Expand All @@ -17,6 +18,7 @@ pub(crate) fn router() -> Router {
)
}

#[tracing::instrument]
pub(crate) fn setup_metrics_recorder() -> PrometheusHandle {
const EXPONENTIAL_SECONDS: &[f64] = &[
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
Expand All @@ -32,6 +34,8 @@ pub(crate) fn setup_metrics_recorder() -> PrometheusHandle {
.unwrap()
}

#[tracing::instrument(skip_all)]
#[allow(clippy::let_with_type_underscore)]
pub(crate) async fn track_metrics<B>(req: Request<B>, next: Next<B>) -> impl IntoResponse {
let start = Instant::now();
let path = if let Some(matched_path) = req.extensions().get::<MatchedPath>() {
Expand Down

0 comments on commit 10366f4

Please sign in to comment.