Crates.io | actix-web-middleware-requestid |
lib.rs | actix-web-middleware-requestid |
version | 3.0.1 |
source | src |
created_at | 2019-12-29 05:06:28.429415 |
updated_at | 2020-09-27 07:26:50.205185 |
description | Request ID middleware for the actix-web framework v1.0+ |
homepage | https://github.com/tonkonogov/actix-web-middleware-requestid |
repository | https://github.com/tonkonogov/actix-web-middleware-requestid |
max_upload_size | |
id | 193158 |
size | 9,353 |
Request ID middleware for the actix-web framework v3.0+
Adds a custom header with a unique token to every request. Also includes a handy actix-web compliant extractor for requests.
Add the package to Cargo.toml:
[dependencies]
actix-web-middleware-requestid = "3.0"
Import and add middleware to your server definition:
use actix_web_middleware_requestid::RequestIDWrapper;
...
fn main() -> std::io::Result<()> {
App::new()
...
.wrap(RequestIDWrapper)
...
}
...
async fn index(id: RequestID) -> HttpResponse {
log::info!("id: {}", id.0);
...
}
For actix-web v1.x use version "1.0" of the same package. The usage pattern and all exported names remain the same.
use actix_web::{middleware, web, App, HttpResponse, HttpServer};
use actix_web_middleware_requestid::{RequestID, RequestIDWrapper};
// actix web application state
pub struct AppState {
pub logger: slog::Logger,
}
fn index((state, id): (web::Data<AppState>, RequestID)) -> HttpResponse {
let logger = state.logger.new(slog::o!("request_id" => id.0));
slog::info!(logger, "i am request");
HttpResponse::Ok()
.content_type("application/json")
.body("{}")
}
const LOG_TPLT: &str = "[Code: %s] [Payload: %b] [TTS: %T], request_id: %{x-request-id}i";
fn init_logger() -> slog::Logger {
use slog::Drain;
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).chan_size(512).build().fuse();
slog::Logger::root(drain, slog::o!())
}
fn main() -> std::io::Result<()> {
// define env vars if missed
dotenv::dotenv().ok();
// initialise the logger
let root_log = init_logger();
// define scope logger (for middleware logging)
let _scope_guard = slog_scope::set_global_logger(root_log.new(slog::o!()));
slog_stdlog::init().unwrap();
// slog wrapper to catch log-based logs
slog_scope::scope(&root_log.new(slog::o!()), || {
HttpServer::new(move || {
App::new()
.data(AppState {
logger: root_log.new(slog::o!()),
})
.wrap(middleware::Logger::new(LOG_TPLT))
.wrap(RequestIDWrapper)
.service(web::resource("/").to(index))
})
.bind("0.0.0.0:8080")?
.run()
})
}
Consider using a similar crate actix-web-requestid
This project is licensed under either of
at your option.