Skip to content

Commit 4ed2794

Browse files
committed
fix all usages of logging, kill me please
1 parent 4ca9405 commit 4ed2794

72 files changed

Lines changed: 1328 additions & 429 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

Cargo.lock

Lines changed: 25 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ codegen-units = 1
3535
serde = { version = "1.0.219", features = ["derive"] }
3636
serde_json = "1.0.150"
3737
sonic-rs = "0.5.3"
38-
insta = { version = "1.42.1", features= ["filters"] }
38+
insta = { version = "1.42.1", features= ["filters", "json", "redactions"] }
3939
criterion = { version = "0.8", features = ["html_reports", "async_tokio"] }
4040
lazy_static = "1.5.0"
4141
dashmap = { version = "6.2.1" }

bin/router/src/jwt/jwks_manager.rs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
use hive_router_config::jwt_auth::{JwksProviderSourceConfig, JwtAuthConfig};
2-
use hive_router_internal::background_tasks::{BackgroundTask, BackgroundTasksManager};
2+
use hive_router_internal::{
3+
background_tasks::{BackgroundTask, BackgroundTasksManager},
4+
telemetry::logging::targets,
5+
};
36
use sonic_rs::from_str;
47
use std::sync::{Arc, RwLock};
58
use tokio::fs::read_to_string;
@@ -29,7 +32,7 @@ impl JwksManager {
2932
.filter_map(|v| match v.get_jwk_set() {
3033
Ok(set) => Some(set),
3134
Err(err) => {
32-
error!("Failed to use JWK set: {}, ignoring", err);
35+
error!(target: targets::JWT, error = ?err, "failed to use jwt set, ignoring this set");
3336

3437
None
3538
}
@@ -79,9 +82,10 @@ impl BackgroundTask for JwksSourceTask {
7982
..
8083
} = &self.0.config
8184
{
82-
debug!(
83-
"Starting remote jwks polling for source: {:?}",
84-
self.0.config
85+
info!(
86+
target: targets::JWT,
87+
source = ?self.0.config,
88+
"starting remote jwks polling for source",
8589
);
8690
let mut tokio_interval = tokio::time::interval(*interval);
8791

@@ -90,10 +94,10 @@ impl BackgroundTask for JwksSourceTask {
9094
_ = tokio_interval.tick() => { match self.0.load_and_store_jwks().await {
9195
Ok(_) => {}
9296
Err(err) => {
93-
error!("Failed to load remote jwks: {}", err);
97+
error!(target: targets::JWT, error = ?err, source = ?self.0.config, "failed to load remote jwks");
9498
}
9599
} }
96-
_ = token.cancelled() => { info!("Jwks source shutting down."); return; }
100+
_ = token.cancelled() => { info!(target: targets::JWT, "jwks source shutting down."); return; }
97101
}
98102
}
99103
}
@@ -117,7 +121,7 @@ impl JwksSource {
117121
let jwks_str = match &self.config {
118122
JwksProviderSourceConfig::Remote { url, .. } => {
119123
let client = reqwest::Client::new();
120-
debug!("loading jwks from a remote source: {}", url);
124+
debug!(target: targets::JWT, url = ?url, "loading jwks from a remote source");
121125

122126
let response_text = client
123127
.get(url)
@@ -131,7 +135,7 @@ impl JwksSource {
131135
response_text
132136
}
133137
JwksProviderSourceConfig::File { file, .. } => {
134-
debug!("loading jwks from a file source: {}", file.absolute);
138+
debug!(target: targets::JWT, path = ?file.absolute, "loading jwks from a file source");
135139

136140
let file_contents = read_to_string(&file.absolute)
137141
.await

bin/router/src/jwt/mod.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::{str::FromStr, sync::Arc};
66

77
use cookie::Cookie;
88
use hive_router_config::jwt_auth::{JwtAuthConfig, JwtAuthPluginLookupLocation};
9-
use hive_router_internal::background_tasks::BackgroundTasksManager;
9+
use hive_router_internal::{background_tasks::BackgroundTasksManager, telemetry::logging::targets};
1010
use http::header::COOKIE;
1111
use jsonwebtoken::{
1212
decode, decode_header,
@@ -94,7 +94,7 @@ impl JwtAuthRuntime {
9494
let raw_cookies = match cookie_raw.to_str() {
9595
Ok(cookies) => cookies.split(';'),
9696
Err(e) => {
97-
warn!("jwt auth failed to convert cookie header to string, ignoring cookie. error: {}", e);
97+
warn!(target: targets::JWT, error = ?e, "jwt auth failed to convert cookie header to string, ignoring cookie");
9898
continue;
9999
}
100100
};
@@ -111,10 +111,7 @@ impl JwtAuthRuntime {
111111
Err(e) => {
112112
// Should we reject the entire request in case of invalid cookies?
113113
// I think it's better to consider this as a user error? maybe return 400?
114-
warn!(
115-
"jwt auth failed to parse cookie value, ignoring cookie. error: {}",
116-
e
117-
);
114+
warn!(target: targets::JWT, error = ?e, "jwt auth failed to parse cookie value, ignoring cookie");
118115
}
119116
}
120117
}
@@ -173,7 +170,7 @@ impl JwtAuthRuntime {
173170
.map(|token_data| (token_data, maybe_prefix, token))
174171
}
175172
Err(e) => {
176-
warn!("jwt plugin failed to lookup token. error: {}", e);
173+
warn!(target: targets::JWT, error = ?e, "jwt plugin failed to lookup token");
177174

178175
Err(JwtError::LookupFailed(e))
179176
}
@@ -311,7 +308,7 @@ impl JwtAuthRuntime {
311308
token_prefix: maybe_prefix,
312309
})),
313310
Err(err) => {
314-
warn!("jwt token error: {:?}", err);
311+
warn!(target: targets::JWT, error = ?err, "jwt token error");
315312
if self.config.require_authentication.is_some_and(|v| v) {
316313
Err((*err).clone())
317314
} else {

bin/router/src/lib.rs

Lines changed: 63 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,14 @@ mod supergraph;
1212
pub mod telemetry;
1313
mod utils;
1414

15+
use http::{
16+
header::{ACCEPT, CONTENT_TYPE, USER_AGENT},
17+
HeaderName,
18+
};
19+
use ntex_http::body::{BodySize, MessageBody};
1520
use std::ops::ControlFlow;
1621
use std::sync::Arc;
17-
use tracing::error;
22+
use tracing::{debug, error};
1823

1924
use crate::{
2025
consts::ROUTER_VERSION,
@@ -61,10 +66,8 @@ pub use hive_router_config::humantime_serde;
6166
use hive_router_config::{load_config, subscriptions::CallbackConfig, HiveRouterConfig};
6267
pub use hive_router_internal::background_tasks;
6368
use hive_router_internal::telemetry::{
64-
logging::{log_http_request_end, log_http_request_start},
65-
otel::tracing_opentelemetry::OpenTelemetrySpanExt,
66-
traces::spans::http_request::HttpServerRequestSpan,
67-
TelemetryContext,
69+
logging::targets, otel::tracing_opentelemetry::OpenTelemetrySpanExt,
70+
traces::spans::http_request::HttpServerRequestSpan, TelemetryContext,
6871
};
6972
pub use hive_router_internal::BoxError;
7073
use hive_router_internal::{
@@ -125,6 +128,17 @@ impl BackgroundTask for CallbackServer {
125128
}
126129
}
127130

131+
#[inline]
132+
fn obtain_header_value<'a>(
133+
header_map: &'a ntex::http::HeaderMap,
134+
header_name: &HeaderName,
135+
) -> &'a str {
136+
header_map
137+
.get(header_name)
138+
.map(|h| h.to_str().unwrap_or(""))
139+
.unwrap_or("")
140+
}
141+
128142
async fn graphql_endpoint_handler(
129143
mut request: HttpRequest,
130144
body_stream: web::types::Payload,
@@ -152,11 +166,42 @@ async fn graphql_endpoint_handler(
152166
.capture_request(&request);
153167

154168
let response = async {
155-
log_http_request_start(&request);
169+
let content_type = obtain_header_value(request.headers(), &CONTENT_TYPE);
170+
let accept = obtain_header_value(request.headers(), &ACCEPT);
171+
let user_agent = obtain_header_value(request.headers(), &USER_AGENT);
172+
173+
info!(
174+
target: targets::HTTP_SERVER,
175+
method = request.method().as_str(),
176+
path = request.path(),
177+
"http request started",
178+
);
179+
180+
debug!(
181+
target: targets::HTTP_SERVER,
182+
query_string = request.query_string(),
183+
content_type,
184+
accept,
185+
user_agent,
186+
"http request attributes",
187+
);
188+
156189
let inner_res =
157190
graphql_endpoint_dispatch(&mut request, body_stream, schema_state, app_state.clone())
158191
.await;
159-
log_http_request_end(&inner_res);
192+
193+
let payload_bytes = match inner_res.body().size() {
194+
BodySize::Empty | BodySize::None => 0,
195+
BodySize::Sized(size) => size as i64,
196+
BodySize::Stream => -1,
197+
};
198+
199+
info!(
200+
target: targets::HTTP_SERVER,
201+
status_code = inner_res.status().as_u16(),
202+
payload_bytes,
203+
"http request completed",
204+
);
160205

161206
inner_res
162207
}
@@ -237,7 +282,7 @@ async fn graphql_endpoint_dispatch(
237282
.take()
238283
.modify_client_response_headers(response.headers_mut())
239284
{
240-
error!(error = %err, "Failed to apply response header rules to the outgoing client response");
285+
error!(target: targets::HEADER_MANIPULATION, error = %err, "failed to apply response header rules to the outgoing client response");
241286
}
242287

243288
// Apply CORS headers to the final response if CORS is configured.
@@ -260,7 +305,7 @@ async fn graphql_endpoint_dispatch(
260305
ControlFlow::Break(updated_response) | ControlFlow::Continue(updated_response),
261306
) => updated_response,
262307
Err(error) => {
263-
warn!(%error, "coprocessor graphql.response stage failed");
308+
warn!(target: targets::COPROCESSOR, error = ?error, "coprocessor graphql.response stage failed");
264309
write_graphql_response_metric_status(request, GraphQLResponseStatus::Error);
265310
handle_pipeline_error(error.into(), request, &app_state, &response_mode)
266311
}
@@ -291,7 +336,7 @@ pub async fn router_entrypoint(plugin_registry: PluginRegistry) -> Result<(), Ro
291336
.prometheus
292337
.as_ref()
293338
.and_then(|prom| prom.to_attached());
294-
info!("hive-router@{} starting...", ROUTER_VERSION);
339+
info!(target: targets::CORE, version = ROUTER_VERSION, "hive-router starting...");
295340
let addr = router_config.address();
296341
let graphql_path = router_config.graphql_path().to_string();
297342
let websocket_path = router_config.websocket_path().map(|p| p.to_string());
@@ -332,8 +377,9 @@ pub async fn router_entrypoint(plugin_registry: PluginRegistry) -> Result<(), Ro
332377
});
333378
if let Some(workers) = workers {
334379
info!(
335-
"configuring HTTP callback server with {} worker(s)",
336-
workers
380+
target: targets::CORE,
381+
workers_count = workers,
382+
"configuring HTTP callback server worker(s)",
337383
);
338384
cb_server_builder = cb_server_builder.workers(workers.get());
339385
}
@@ -386,7 +432,7 @@ pub async fn router_entrypoint(plugin_registry: PluginRegistry) -> Result<(), Ro
386432
});
387433

388434
if let Some(workers) = workers {
389-
info!("configuring HTTP server with {} worker(s)", workers);
435+
info!(target: targets::CORE, workers_count = workers, "configuring HTTP server worker(s)");
390436
server = server.workers(workers.get());
391437
}
392438

@@ -426,7 +472,7 @@ pub async fn router_entrypoint(plugin_registry: PluginRegistry) -> Result<(), Ro
426472
.await
427473
.map_err(RouterInitError::HttpServerStartError);
428474

429-
info!("server stopped, clearing background tasks");
475+
info!(target: targets::CORE, "router stopped, clearing background tasks");
430476
bg_tasks_manager.shutdown();
431477
telemetry.graceful_shutdown().await;
432478

@@ -437,7 +483,8 @@ pub async fn router_entrypoint(plugin_registry: PluginRegistry) -> Result<(), Ro
437483

438484
pub async fn invoke_shutdown_hooks(shared_state: &RouterSharedState) {
439485
if let Some(plugins) = &shared_state.plugins {
440-
info!("invoking plugin shutdown hooks");
486+
debug!(target: targets::CORE, "invoking plugin shutdown hooks");
487+
441488
for plugin in plugins.as_ref() {
442489
plugin.on_shutdown().await;
443490
}
@@ -676,7 +723,7 @@ pub fn init_rustls_crypto_provider() {
676723
.install_default()
677724
.is_err()
678725
{
679-
warn!("Rustls crypto provider already installed");
726+
error!(target: targets::TLS, "rustls crypto provider already installed, ignoring");
680727
}
681728
}
682729

bin/router/src/pipeline/active_subscriptions.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::sync::Arc;
22

33
use bytes::Bytes;
44
use dashmap::DashMap;
5+
use hive_router_internal::telemetry::logging::targets;
56
use hive_router_plan_executor::response::graphql_error::GraphQLError;
67
use tokio::sync::broadcast;
78
use tracing::trace;
@@ -54,7 +55,7 @@ impl ActiveSubscriptions {
5455
_guard: guard,
5556
};
5657

57-
trace!(subscription_id = %id, "registered new subscription");
58+
trace!(target: targets::SUBSCRIPTIONS, subscription_id = %id, "registered new subscription");
5859

5960
(handle, receiver)
6061
}
@@ -93,6 +94,6 @@ impl ProducerHandle {
9394
impl Drop for ProducerHandle {
9495
fn drop(&mut self) {
9596
self.map.remove(&self.id);
96-
trace!(subscription_id = %self.id, "producer dropped, upstream closed");
97+
trace!(target: targets::SUBSCRIPTIONS, subscription_id = %self.id, "producer dropped, upstream closed");
9798
}
9899
}

bin/router/src/pipeline/authorization/mod.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ use crate::pipeline::normalize::{hash_normalized_operation, GraphQLNormalization
2929
use hive_router_config::authorization::UnauthorizedMode;
3030
use hive_router_config::HiveRouterConfig;
3131
use hive_router_internal::authorization::metadata::AuthorizationMetadata;
32+
use hive_router_internal::telemetry::logging::targets;
3233
use hive_router_plan_executor::execution::client_request_details::JwtRequestDetails;
3334
use hive_router_plan_executor::execution::plan::CoerceVariablesPayload;
3435
use hive_router_plan_executor::introspection::schema::SchemaMetadata;
@@ -180,7 +181,8 @@ pub fn apply_authorization_to_operation(
180181
}
181182

182183
if reject_mode {
183-
tracing::debug!("Request rejected due to unauthorized fields and reject mode being set");
184+
tracing::warn!(target: targets::AUTHORIZATION, "request rejected due to unauthorized fields and reject mode being set");
185+
184186
return AuthorizationDecision::Reject {
185187
errors: collection_result.errors,
186188
};

0 commit comments

Comments
 (0)