Merge pull request #889 from joshtriplett/stop-exporting-logging

Stop re-exporting logging details from tide::log
This commit is contained in:
Josh Triplett 2022-07-21 11:54:59 -07:00 committed by GitHub
commit fb8f6d4716
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 55 additions and 86 deletions

View File

@ -27,7 +27,7 @@ rustdoc-args = ["--cfg", "feature=\"docs\""]
default = ["h1-server"]
cookies = ["http-types/cookies"]
h1-server = ["async-h1"]
logger = ["femme"]
logger = []
docs = ["unstable"]
sessions = ["async-session", "cookies"]
sse = ["async-sse"]
@ -39,7 +39,6 @@ async-session = { version = "3.0", optional = true }
async-sse = { version = "5.1.0", optional = true }
async-std = { version = "1.6.5", features = ["unstable"] }
async-trait = "0.1.41"
femme = { version = "2.1.1", optional = true }
futures-util = "0.3.6"
http-client = { version = "6.1.0", default-features = false }
http-types = { version = "2.11.0", default-features = false, features = ["fs"] }
@ -54,7 +53,9 @@ regex = "1.5.5"
[dev-dependencies]
async-std = { version = "1.6.5", features = ["unstable", "attributes"] }
criterion = "0.3.3"
femme = "2.1.1"
juniper = "0.14.2"
kv-log-macro = "1.0.7"
lazy_static = "1.4.0"
logtest = "2.0.0"
portpicker = "0.1.0"

View File

@ -2,7 +2,7 @@
#[async_std::main]
async fn main() -> Result<(), std::io::Error> {
use std::{env, net::TcpListener, os::unix::io::FromRawFd};
tide::log::start();
femme::start();
let mut app = tide::new();
app.with(tide::log::LogMiddleware::new());
app.at("/").get(|_| async { Ok(CHANGE_THIS_TEXT) });

View File

@ -2,7 +2,7 @@ use tide::Body;
#[async_std::main]
async fn main() -> Result<(), std::io::Error> {
tide::log::start();
femme::start();
let mut app = tide::new();
app.with(tide::log::LogMiddleware::new());
app.at("/").get(|_| async {

View File

@ -2,7 +2,7 @@ use tide::Request;
#[async_std::main]
async fn main() -> Result<(), std::io::Error> {
tide::log::start();
femme::start();
let mut app = tide::new();
app.with(tide::log::LogMiddleware::new());

View File

@ -21,7 +21,7 @@ async fn remove_cookie(_req: Request<()>) -> tide::Result {
#[async_std::main]
async fn main() -> Result<(), std::io::Error> {
tide::log::start();
femme::start();
let mut app = tide::new();
app.with(tide::log::LogMiddleware::new());

View File

@ -5,7 +5,7 @@ use tide::{Body, Request, Response, Result, StatusCode};
#[async_std::main]
async fn main() -> Result<()> {
tide::log::start();
femme::start();
let mut app = tide::new();
app.with(tide::log::LogMiddleware::new());

View File

@ -1,6 +1,6 @@
#[async_std::main]
async fn main() -> Result<(), std::io::Error> {
tide::log::start();
femme::start();
let mut app = tide::new();
app.with(tide::log::LogMiddleware::new());

View File

@ -9,7 +9,7 @@ struct Cat {
#[async_std::main]
async fn main() -> tide::Result<()> {
tide::log::start();
femme::start();
let mut app = tide::new();
app.with(tide::log::LogMiddleware::new());

View File

@ -3,6 +3,7 @@ use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use kv_log_macro::trace;
use tide::http::mime;
use tide::utils::{After, Before};
use tide::{Middleware, Next, Request, Response, Result, StatusCode};
@ -31,7 +32,7 @@ fn user_loader<'a>(
) -> Pin<Box<dyn Future<Output = Result> + Send + 'a>> {
Box::pin(async {
if let Some(user) = request.state().find_user().await {
tide::log::trace!("user loaded", {user: user.name});
trace!("user loaded", {user: user.name});
request.set_ext(user);
Ok(next.run(request).await)
// this middleware only needs to run before the endpoint, so
@ -64,7 +65,7 @@ struct RequestCount(usize);
impl<State: Clone + Send + Sync + 'static> Middleware<State> for RequestCounterMiddleware {
async fn handle(&self, mut req: Request<State>, next: Next<'_, State>) -> Result {
let count = self.requests_counted.fetch_add(1, Ordering::Relaxed);
tide::log::trace!("request counter", { count: count });
trace!("request counter", { count: count });
req.set_ext(RequestCount(count));
let mut res = next.run(req).await;
@ -91,7 +92,7 @@ const INTERNAL_SERVER_ERROR_HTML_PAGE: &str = "<html><body>
#[async_std::main]
async fn main() -> Result<()> {
tide::log::start();
femme::start();
let mut app = tide::with_state(UserDatabase::default());
app.with(After(|response: Response| async move {

View File

@ -1,6 +1,6 @@
#[async_std::main]
async fn main() -> Result<(), std::io::Error> {
tide::log::start();
femme::start();
let mut app = tide::new();
app.with(tide::log::LogMiddleware::new());
app.at("/").get(|_| async { Ok("Root") });

View File

@ -2,7 +2,7 @@ use tide::{Redirect, Response, StatusCode};
#[async_std::main]
async fn main() -> Result<(), std::io::Error> {
tide::log::start();
femme::start();
let mut app = tide::new();
app.with(tide::log::LogMiddleware::new());
app.at("/").get(|_| async { Ok("Root") });

View File

@ -1,6 +1,6 @@
#[async_std::main]
async fn main() -> Result<(), std::io::Error> {
tide::log::start();
femme::start();
let mut app = tide::new();
app.with(tide::log::LogMiddleware::new());

View File

@ -16,7 +16,7 @@ impl State {
#[async_std::main]
async fn main() -> tide::Result<()> {
tide::log::start();
femme::start();
let mut app = tide::with_state(State::new());
app.with(tide::log::LogMiddleware::new());
app.at("/").get(|req: tide::Request<State>| async move {

View File

@ -1,6 +1,6 @@
#[async_std::main]
async fn main() -> Result<(), std::io::Error> {
tide::log::start();
femme::start();
let mut app = tide::new();
app.with(tide::log::LogMiddleware::new());
app.at("/").get(|_| async { Ok("visit /src/*") });

View File

@ -3,6 +3,7 @@ use std::path::Path;
use std::sync::Arc;
use async_std::{fs::OpenOptions, io};
use kv_log_macro::info;
use tempfile::TempDir;
use tide::prelude::*;
use tide::{Body, Request, Response, StatusCode};
@ -26,7 +27,7 @@ impl TempDirState {
#[async_std::main]
async fn main() -> Result<(), IoError> {
tide::log::start();
femme::start();
let mut app = tide::with_state(TempDirState::try_new()?);
app.with(tide::log::LogMiddleware::new());
@ -48,7 +49,7 @@ async fn main() -> Result<(), IoError> {
let bytes_written = io::copy(req, file).await?;
tide::log::info!("file written", {
info!("file written", {
bytes: bytes_written,
path: fs_path.canonicalize()?.to_str()
});

View File

@ -1,7 +1,7 @@
use crate::log;
use crate::{Body, Endpoint, Request, Response, Result, StatusCode};
use async_std::path::PathBuf as AsyncPathBuf;
use kv_log_macro::{info, warn};
use std::path::{Path, PathBuf};
use std::{ffi::OsStr, io};
@ -40,17 +40,17 @@ where
}
}
log::info!("Requested file: {:?}", file_path);
info!("Requested file: {:?}", file_path);
let file_path = AsyncPathBuf::from(file_path);
if !file_path.starts_with(&self.dir) {
log::warn!("Unauthorized attempt to read: {:?}", file_path);
warn!("Unauthorized attempt to read: {:?}", file_path);
Ok(Response::new(StatusCode::Forbidden))
} else {
match Body::from_file(&file_path).await {
Ok(body) => Ok(Response::builder(StatusCode::Ok).body(body).build()),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
log::warn!("File not found: {:?}", &file_path);
warn!("File not found: {:?}", &file_path);
Ok(Response::new(StatusCode::NotFound))
}
Err(e) => Err(e.into()),

View File

@ -1,10 +1,10 @@
use crate::log;
use crate::{Body, Endpoint, Request, Response, Result, StatusCode};
use std::io;
use std::path::Path;
use async_std::path::PathBuf as AsyncPathBuf;
use async_trait::async_trait;
use kv_log_macro::warn;
pub(crate) struct ServeFile {
path: AsyncPathBuf,
@ -26,7 +26,7 @@ impl<State: Clone + Send + Sync + 'static> Endpoint<State> for ServeFile {
match Body::from_file(&self.path).await {
Ok(body) => Ok(Response::builder(StatusCode::Ok).body(body).build()),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
log::warn!("File not found: {:?}", &self.path);
warn!("File not found: {:?}", &self.path);
Ok(Response::new(StatusCode::NotFound))
}
Err(e) => Err(e.into()),

View File

@ -32,9 +32,7 @@
//!
//! #[async_std::main]
//! async fn main() -> tide::Result<()> {
//! tide::log::start();
//! let mut app = tide::new();
//! app.with(tide::log::LogMiddleware::new());
//! app.at("/orders/shoes").post(order_shoes);
//! app.listen("127.0.0.1:8080").await?;
//! Ok(())

View File

@ -13,7 +13,6 @@ use futures_util::stream::{futures_unordered::FuturesUnordered, StreamExt};
/// ```rust
/// fn main() -> Result<(), std::io::Error> {
/// async_std::task::block_on(async {
/// tide::log::start();
/// let mut app = tide::new();
/// app.at("/").get(|_| async { Ok("Hello, world!") });
///

View File

@ -4,6 +4,7 @@ use crate::Server;
use std::fmt::{self, Debug, Display, Formatter};
use async_std::io;
use kv_log_macro::info;
use crate::listener::ListenInfo;
@ -15,7 +16,6 @@ use crate::listener::ListenInfo;
/// ```rust
/// fn main() -> Result<(), std::io::Error> {
/// async_std::task::block_on(async {
/// tide::log::start();
/// let mut app = tide::new();
/// app.at("/").get(|_| async { Ok("Hello, world!") });
///
@ -109,7 +109,7 @@ where
return Ok(());
}
Err(e) => {
crate::log::info!("unable to bind", {
info!("unable to bind", {
listener: listener.to_string(),
error: e.to_string()
});

View File

@ -1,13 +1,14 @@
use super::{is_transient_error, ListenInfo};
use crate::listener::Listener;
use crate::{log, Server};
use crate::Server;
use std::fmt::{self, Display, Formatter};
use async_std::net::{self, SocketAddr, TcpStream};
use async_std::prelude::*;
use async_std::{io, task};
use kv_log_macro::error;
/// This represents a tide [Listener](crate::listener::Listener) that
/// wraps an [async_std::net::TcpListener]. It is implemented as an
@ -56,7 +57,7 @@ fn handle_tcp<State: Clone + Send + Sync + 'static>(app: Server<State>, stream:
});
if let Err(error) = fut.await {
log::error!("async-h1 error", { error: error.to_string() });
error!("async-h1 error", { error: error.to_string() });
}
});
}
@ -105,7 +106,7 @@ where
Err(ref e) if is_transient_error(e) => continue,
Err(error) => {
let delay = std::time::Duration::from_millis(500);
crate::log::error!("Error: {}. Pausing for {:?}.", error, delay);
error!("Error: {}. Pausing for {:?}.", error, delay);
task::sleep(delay).await;
continue;
}

View File

@ -1,7 +1,7 @@
use super::{is_transient_error, ListenInfo};
use crate::listener::Listener;
use crate::{log, Server};
use crate::Server;
use std::fmt::{self, Display, Formatter};
@ -9,6 +9,7 @@ use async_std::os::unix::net::{self, SocketAddr, UnixStream};
use async_std::path::PathBuf;
use async_std::prelude::*;
use async_std::{io, task};
use kv_log_macro::error;
/// This represents a tide [Listener](crate::listener::Listener) that
/// wraps an [async_std::os::unix::net::UnixListener]. It is implemented as an
@ -57,7 +58,7 @@ fn handle_unix<State: Clone + Send + Sync + 'static>(app: Server<State>, stream:
});
if let Err(error) = fut.await {
log::error!("async-h1 error", { error: error.to_string() });
error!("async-h1 error", { error: error.to_string() });
}
});
}
@ -103,7 +104,7 @@ where
Err(ref e) if is_transient_error(e) => continue,
Err(error) => {
let delay = std::time::Duration::from_millis(500);
crate::log::error!("Error: {}. Pausing for {:?}.", error, delay);
error!("Error: {}. Pausing for {:?}.", error, delay);
task::sleep(delay).await;
continue;
}

View File

@ -1,4 +1,5 @@
use crate::log;
use kv_log_macro::{error, info, warn};
use crate::{Middleware, Next, Request};
/// Log all incoming requests and responses.
@ -38,7 +39,7 @@ impl LogMiddleware {
let path = req.url().path().to_owned();
let method = req.method().to_string();
log::info!("<-- Request received", {
info!("<-- Request received", {
method: method,
path: path,
});
@ -47,7 +48,7 @@ impl LogMiddleware {
let status = response.status();
if status.is_server_error() {
if let Some(error) = response.error() {
log::error!("Internal error --> Response sent", {
error!("Internal error --> Response sent", {
message: format!("{:?}", error),
error_type: error.type_name(),
method: method,
@ -56,7 +57,7 @@ impl LogMiddleware {
duration: format!("{:?}", start.elapsed()),
});
} else {
log::error!("Internal error --> Response sent", {
error!("Internal error --> Response sent", {
method: method,
path: path,
status: format!("{} - {}", status as u16, status.canonical_reason()),
@ -65,7 +66,7 @@ impl LogMiddleware {
}
} else if status.is_client_error() {
if let Some(error) = response.error() {
log::warn!("Client error --> Response sent", {
warn!("Client error --> Response sent", {
message: format!("{:?}", error),
error_type: error.type_name(),
method: method,
@ -74,7 +75,7 @@ impl LogMiddleware {
duration: format!("{:?}", start.elapsed()),
});
} else {
log::warn!("Client error --> Response sent", {
warn!("Client error --> Response sent", {
method: method,
path: path,
status: format!("{} - {}", status as u16, status.canonical_reason()),
@ -82,7 +83,7 @@ impl LogMiddleware {
});
}
} else {
log::info!("--> Response sent", {
info!("--> Response sent", {
method: method,
path: path,
status: format!("{} - {}", status as u16, status.canonical_reason()),

View File

@ -1,41 +1,5 @@
//! Event logging types.
//!
//! # Examples
//!
//! ```no_run
//! use tide::log;
//!
//! log::start();
//!
//! log::info!("Hello cats");
//! log::debug!("{} wants tuna", "Nori");
//! log::error!("We're out of tuna!");
//! log::info!("{} are hungry", "cats", {
//! cat_1: "Chashu",
//! cat_2: "Nori",
//! });
//! ```
pub use kv_log_macro::{debug, error, info, log, trace, warn};
pub use kv_log_macro::{max_level, Level};
//! Support for logging in tide; see [`LogMiddleware`].
mod middleware;
#[cfg(feature = "logger")]
pub use femme::LevelFilter;
pub use middleware::LogMiddleware;
/// Start logging.
#[cfg(feature = "logger")]
pub fn start() {
femme::start();
crate::log::info!("Logger started", { level: "Info" });
}
/// Start logging with a log level.
#[cfg(feature = "logger")]
pub fn with_level(level: LevelFilter) {
femme::with_level(level);
crate::log::info!("Logger started", { level: format!("{}", level) });
}

View File

@ -5,9 +5,10 @@ use std::sync::Arc;
use crate::endpoint::MiddlewareEndpoint;
use crate::fs::{ServeDir, ServeFile};
use crate::log;
use crate::{router::Router, Endpoint, Middleware};
use kv_log_macro::trace;
/// A handle to a route.
///
/// All HTTP requests are made against resources. After using [`Server::at`] (or
@ -81,7 +82,7 @@ impl<'a, State: Clone + Send + Sync + 'static> Route<'a, State> {
where
M: Middleware<State>,
{
log::trace!(
trace!(
"Adding middleware {} to route {:?}",
middleware.name(),
self.path

View File

@ -2,11 +2,11 @@
use async_std::io;
use async_std::sync::Arc;
use kv_log_macro::{info, trace};
#[cfg(feature = "cookies")]
use crate::cookies;
use crate::listener::{Listener, ToListener};
use crate::log;
use crate::middleware::{Middleware, Next};
use crate::router::{Router, Selection};
use crate::{Endpoint, Request, Route};
@ -179,7 +179,7 @@ where
where
M: Middleware<State>,
{
log::trace!("Adding middleware {}", middleware.name());
trace!("Adding middleware {}", middleware.name());
let m = Arc::get_mut(&mut self.middleware)
.expect("Registering middleware is not possible after the Server has started");
m.push(Arc::new(middleware));
@ -207,7 +207,7 @@ where
let mut listener = listener.to_listener()?;
listener.bind(self).await?;
for info in listener.info().iter() {
log::info!("Server listening on {}", info);
info!("Server listening on {}", info);
}
listener.accept().await?;
Ok(())

View File

@ -11,6 +11,7 @@ use async_session::{
hmac::{Hmac, Mac, NewMac},
sha2::Sha256,
};
use kv_log_macro::error;
const BASE64_DIGEST_LEN: usize = 44;
@ -98,7 +99,7 @@ where
if session.is_destroyed() {
if let Err(e) = self.store.destroy_session(session).await {
crate::log::error!("unable to destroy session", { error: e.to_string() });
error!("unable to destroy session", { error: e.to_string() });
}
if let Some(mut cookie) = cookie {