use std::sync::Arc;
use laravel::Application;
use laravel::config::Env;
use laravel::config::logging::LogChannel;
use laravel::http::{Request, RequestId};
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use serde_json::Value;
use crate::support::{self, TempDir};
pub(crate) use support::Lines;
fn app(env: Env) -> Application {
Application::configure()
.replace_env(env)
.with_routing(|routing, _| {
routing.routes(|route: &mut Router| {
route.get("/users/{user}", |request: Request| async move {
tracing::info!("looking up the user");
request.id().unwrap_or_default().to_owned()
});
route.get("/id", |id: RequestId| async move { id.to_string() });
route.get("/broken", || async {
std::fs::read("/no/such/file")?;
Ok::<_, laravel::Error>("read")
});
route.get("/panic", || async {
panic!("the disk is full");
#[expect(unreachable_code, reason = "the handler's response type")]
""
});
});
})
.create()
}
fn daily_log(root: &std::path::Path) -> String {
let file = std::fs::read_dir(root.join("storage/logs"))
.unwrap()
.map(|entry| entry.unwrap().path())
.find(|path| path.extension().is_some_and(|extension| extension == "log"))
.expect("a log file");
std::fs::read_to_string(file).unwrap()
}
#[tokio::test]
async fn responses_carry_their_request_id() {
let response = app(Env::default()).get("/users/1").await;
let id = response.header("x-request-id").expect("a request ID");
assert_eq!(id.len(), 32);
assert_eq!(response.text(), id, "the handler sees the same ID");
}
#[tokio::test]
async fn request_ids_from_upstream_are_kept() {
app(Env::default())
.get("/id")
.header("x-request-id", "lb-42")
.await
.assert_header("x-request-id", "lb-42")
.assert_see("lb-42");
}
#[tokio::test]
async fn log_lines_carry_the_requests_fields() {
let (lines, _guard) = Lines::capture();
let response = app(Env::default()).get("/users/1").await;
let id = response.header("x-request-id").unwrap();
let line = lines.find("looking up the user");
assert_eq!(line["span"]["id"], id);
assert_eq!(line["span"]["method"], "GET");
assert_eq!(line["span"]["path"], "/users/1");
assert_eq!(line["span"]["route"], "/users/{user}");
}
#[tokio::test]
async fn every_request_is_logged_with_its_status() {
let (lines, _guard) = Lines::capture();
app(Env::from_iter([("APP_ENV", "local")]))
.get("/missing")
.await
.assert_not_found();
let line = lines.find("GET /missing 404");
assert_eq!(line["level"], "INFO");
assert_eq!(line["fields"]["status"], 404);
}
#[tokio::test]
async fn requests_are_logged_once_their_response_is_sent_or_the_client_leaves() {
use std::time::Duration;
use laravel::http::sse::EventStream;
use laravel::http::{Download, Streamed};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let (lines, _guard) = Lines::capture();
let app = Application::configure()
.replace_env(Env::from_iter([("APP_ENV", "local")]))
.with_routing(|routing, _| {
routing.routes(|route: &mut Router| {
route.get("/report", || async {
Streamed::channel(async |sender| {
for part in ["one\n", "two\n", "three\n"] {
sender.send(part).await?;
laravel::task::sleep(Duration::from_millis(100)).await;
}
Ok(())
})
});
route.get("/stream", || async {
Streamed::channel(async |sender| {
loop {
sender.send("line\n").await?;
laravel::task::sleep(Duration::from_millis(10)).await;
}
})
});
route.get("/events", || async {
EventStream::new(laravel::stream::stream! {
loop {
yield "tick".to_owned();
laravel::task::sleep(Duration::from_millis(10)).await;
}
})
});
route.get("/download", || async {
Download::stream(
"export.csv",
laravel::stream::iter(std::iter::repeat(vec![b'x'; 64 * 1024])),
)
});
route.get("/cached", || async {
(laravel::http::StatusCode::NOT_MODIFIED, "unchanged")
});
route.get("/slow", || async {
std::future::pending::<()>().await;
""
});
});
})
.create();
let address = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap();
let server = tokio::spawn(app.serve(address));
let line = async |path: &str| {
let prefix = format!("GET {path} ");
for _ in 0..500 {
if let Some(line) = lines.json().into_iter().find(|line| {
line["fields"]["message"]
.as_str()
.is_some_and(|message| message.starts_with(&prefix))
}) {
return line;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("no line for {path}: {:#?}", lines.json());
};
let leave = async |path: &str| {
let mut client = loop {
match tokio::net::TcpStream::connect(address).await {
Ok(client) => break client,
Err(_) => tokio::time::sleep(Duration::from_millis(10)).await,
}
};
let request = format!("GET {path} HTTP/1.1\r\nHost: localhost\r\n\r\n");
client.write_all(request.as_bytes()).await.unwrap();
let mut buffer = [0; 1024];
let _ = tokio::time::timeout(Duration::from_millis(200), client.read(&mut buffer)).await;
};
let started = std::time::Instant::now();
let body = get_over_tcp(address, "/report").await;
assert_eq!(body, "one\ntwo\nthree\n");
let report = line("/report").await;
assert_eq!(report["fields"]["status"], 200);
let logged = report["fields"]["duration_ms"].as_f64().unwrap();
assert!(
(200.0..=started.elapsed().as_secs_f64() * 1000.0).contains(&logged),
"the line should time the whole stream: {report}"
);
get_over_tcp(address, "/cached").await;
assert_eq!(line("/cached").await["fields"]["status"], 304);
for path in ["/stream", "/events", "/download", "/slow"] {
leave(path).await;
assert_eq!(line(path).await["fields"]["status"], 499, "{path}");
}
server.abort();
}
async fn get_over_tcp(address: std::net::SocketAddr, path: &str) -> String {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let mut client = loop {
match tokio::net::TcpStream::connect(address).await {
Ok(client) => break client,
Err(_) => tokio::time::sleep(std::time::Duration::from_millis(10)).await,
}
};
client
.write_all(format!("GET {path} HTTP/1.0\r\nHost: localhost\r\n\r\n").as_bytes())
.await
.unwrap();
let mut response = String::new();
client.read_to_string(&mut response).await.unwrap();
response.split_once("\r\n\r\n").unwrap().1.to_owned()
}
#[tokio::test]
async fn requests_are_logged_quietly_outside_local_development() {
for environment in ["staging", "production"] {
let (lines, _guard) = Lines::capture();
app(Env::from_iter([("APP_ENV", environment)]))
.get("/missing")
.await
.assert_not_found();
let line = lines.find("GET /missing 404");
assert_eq!(line["level"], "DEBUG", "{environment}");
assert_eq!(line["fields"]["status"], 404, "{environment}");
}
}
#[tokio::test]
async fn panics_are_reported_with_where_they_happened() {
let (lines, _guard) = Lines::capture();
app(Env::from_iter([("APP_DEBUG", "true")]))
.get("/panic")
.header("accept", "application/json")
.await
.assert_internal_server_error();
let report = lines.report();
let message = report["fields"]["message"].as_str().unwrap();
assert!(message.starts_with("panic at tests/logging.rs:"), "{message}");
assert!(message.ends_with(": the disk is full"), "{message}");
assert_eq!(report["fields"]["type"], "laravel::errors::panic::Panic");
let location = report["fields"]["location"].as_str().unwrap();
assert!(
message.starts_with(&format!("panic at {location}: ")),
"where it panicked, not the kernel's: {report}"
);
}
#[tokio::test]
async fn failures_are_logged_with_where_they_happened() {
let (lines, _guard) = Lines::capture();
app(Env::default()).get("/broken").await.assert_internal_server_error();
let report = lines.report();
assert_eq!(report["fields"]["message"], "No such file or directory (os error 2)");
let location = report["fields"]["location"].as_str().unwrap();
assert!(
location.starts_with("tests/logging.rs:"),
"the `?` in the handler: {location}"
);
}
#[tokio::test]
async fn the_logger_writes_to_every_channel_and_layer() {
let root = TempDir::new("logs");
let layer = Lines::default();
let writer = layer.clone();
let app = Application::configure()
.replace_env(Env::from_iter([
("APP_BASE_PATH", root.to_str().unwrap()),
("WORKFLOW_STORE", "memory"),
]))
.with_config(|config, _| {
config.logging.channels = vec![LogChannel::daily().level("warn"), LogChannel::stderr()];
})
.with_logging(move |logging, _| {
logging.layer(tracing_subscriber::fmt::layer().json().with_writer(writer));
})
.create();
let guard = app.init_logging().expect("the logger should install");
tracing::info!("an info line");
tracing::warn!("a warning");
{
use tracing::Instrument;
app.scope(async || {
async {
laravel::context::add("task_tenant", "acme");
laravel::task::spawn(async { tracing::warn!("async task log") })
.await
.unwrap();
laravel::task::spawn_blocking(|| tracing::warn!("blocking task log"))
.await
.unwrap();
let (send, receive) = tokio::sync::oneshot::channel();
laravel::task::background(async move {
tracing::warn!("background task log");
send.send(()).unwrap();
Ok(())
})
.unwrap();
tokio::time::timeout(std::time::Duration::from_secs(5), receive)
.await
.unwrap()
.unwrap();
}
.instrument(tracing::info_span!("task_parent"))
.await
})
.await;
}
app.scope(async || ShipOrder.start().on_connection("sync").await)
.await
.unwrap();
drop(guard);
let file = daily_log(&root);
assert!(file.contains("a warning"));
assert!(!file.contains("an info line"), "the daily channel only takes warnings");
layer.find("an info line");
layer.find("a warning");
for message in ["async task log", "blocking task log"] {
assert_eq!(layer.find(message)["span"]["name"], "task_parent");
let line = file.lines().find(|line| line.contains(message)).unwrap();
assert!(line.contains("task_tenant"));
assert!(line.contains("acme"));
}
let background = layer.find("background task log");
assert_eq!(background["span"]["name"], "background");
assert!(
background["spans"]
.as_array()
.is_some_and(|spans| spans.iter().any(|span| span["name"] == "task_parent")),
"{background}",
);
let bg_line = file.lines().find(|line| line.contains("background task log")).unwrap();
assert!(bg_line.contains("task_tenant"));
assert!(bg_line.contains("acme"));
let label = layer.find("label printed");
let step = &label["span"];
assert_eq!(step["workflow.name"], "orders.ship", "{label}");
assert_eq!(step["workflow.step"], "print label", "{label}");
assert_eq!(step["workflow.attempt"], 1, "{label}");
for short in ["run", "workflow", "step", "attempt"] {
assert!(
step.get(short).is_none(),
"the step's span doesn't repeat `{short}`: {label}"
);
}
let run = step["workflow.run"].as_str().expect("the run's ID");
let label_line = file.lines().find(|line| line.contains("label printed")).unwrap();
for field in [
format!("workflow.run={run}"),
"workflow.name=\"orders.ship\"".to_owned(),
"workflow.step=\"print label\"".to_owned(),
"workflow.attempt=1".to_owned(),
] {
assert!(label_line.contains(&field), "text lines show `{field}`: {label_line}");
}
}
#[tokio::test]
async fn fallback_requests_are_logged_as_the_fallback() {
let (lines, _guard) = Lines::capture();
Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.routes(|route: &mut Router| {
route.fallback(|| async { "nothing here" });
});
})
.create()
.get("/anywhere")
.await
.assert_ok();
assert_eq!(lines.find("GET /anywhere 200")["span"]["route"], "/{fallback}");
}
#[tokio::test]
async fn health_checks_are_logged_quietly() {
let (lines, _guard) = Lines::capture();
Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.health("/up");
})
.create()
.get("/up")
.await
.assert_ok();
assert_eq!(lines.find("GET /up 200")["level"], "DEBUG");
}
#[tokio::test]
async fn commands_run_in_a_span_that_holds_their_lines_and_failures() {
use laravel::testing::MakesConsoleRequests;
let (lines, _guard) = Lines::capture();
let app = app(Env::default());
app.command("cache:clear").await.assert_successful();
app.command("cache:clear missing-store").await.assert_exit_code(1);
let spans = |line: &Value| line["spans"].clone();
let command = serde_json::json!([{ "name": "command", "command": "cache:clear", "otel.name": "cache:clear" }]);
assert_eq!(
spans(&lines.find("Cache flushed")),
serde_json::json!([
{ "name": "command", "command": "cache:clear", "otel.name": "cache:clear" },
{ "name": "cache", "cache.store": "memory", "otel.kind": "client", "otel.name": "cache.flush" },
]),
);
assert_eq!(spans(&lines.find("cache store `missing-store` isn't defined")), command);
let finished: Vec<_> = lines
.json()
.into_iter()
.filter(|line| line["fields"]["message"] == "Command finished")
.collect();
assert_eq!(finished.len(), 2);
assert_eq!(finished[0]["target"], "laravel::console");
assert_eq!(finished[0]["fields"]["exit_code"], 0);
assert_eq!(finished[1]["fields"]["exit_code"], 1);
assert_eq!(
spans(&finished[1]),
serde_json::json!([{
"name": "command",
"command": "cache:clear",
"otel.name": "cache:clear",
"otel.status_code": "error",
"process.exit.code": 1,
}]),
"the command span has its exit code once it's finished",
);
assert!(finished[0]["fields"]["duration_ms"].as_f64().is_some());
}
#[test]
fn local_request_lines_are_concise_without_changing_other_logs() {
use laravel::config::logging::LogFormat;
use std::process::Command;
if let Some(root) = std::env::var_os("LARAVEL_TEST_LEAN_REQUEST_LOGS") {
let environment = std::env::var("LARAVEL_TEST_REQUEST_ENV").unwrap();
let app = Application::configure()
.replace_env(Env::from_iter([("APP_ENV", environment.as_str())]))
.with_config(|config, _| {
config.app.base_path = root.into();
config.logging.channels = vec![
LogChannel::stderr(),
LogChannel::stdout().format(LogFormat::Json),
LogChannel::daily(),
];
})
.with_routing(|routing, _| {
routing.routes(|route| {
route.get("/users/{user}", || async {
laravel::context::add("tenant", "acme");
tracing::warn!(
target: "laravel::request",
status = 200,
duration_ms = 0.5,
reason = %"the card was declined",
"application request warning"
);
"user"
});
route.options("/ready", || async { "ready" });
route.get("/redirect", || async { laravel::http::StatusCode::FOUND });
route.get("/failure", || async {
laravel::http::StatusCode::INTERNAL_SERVER_ERROR
});
});
})
.create();
let guard = app.init_logging().unwrap();
tokio::runtime::Runtime::new().unwrap().block_on(async {
app.get("/users/7").await.assert_ok();
app.request(laravel::http::Method::OPTIONS, "/ready").await.assert_ok();
app.get("/missing").await.assert_not_found();
app.get("/redirect").await.assert_status(302);
app.get("/failure").await.assert_status(500);
});
drop(guard);
return;
}
for (environment, ansi) in [
("local", false),
("local", true),
("staging", false),
("production", false),
] {
let root = TempDir::new("request-logs");
let output = Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"logging::local_request_lines_are_concise_without_changing_other_logs",
"--nocapture",
])
.env("LARAVEL_TEST_LEAN_REQUEST_LOGS", root.as_os_str())
.env("LARAVEL_TEST_REQUEST_ENV", environment)
.env("NO_COLOR", if ansi { "" } else { "1" })
.env("FORCE_COLOR", if ansi { "1" } else { "0" })
.env("COLORTERM", "truecolor")
.env("TERM", "xterm-256color")
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
let raw = String::from_utf8(output.stderr).unwrap();
let stderr = console::strip_ansi_codes(&raw);
let stdout = String::from_utf8(output.stdout).unwrap();
let file = daily_log(&root);
let json: Vec<Value> = stdout
.lines()
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
.collect();
if environment == "local" {
let request = stderr
.lines()
.find(|line| line.starts_with("GET 200 /users/7"))
.unwrap();
let missing = stderr.lines().find(|line| line.contains("/missing")).unwrap();
assert!(request.starts_with("GET 200 /users/7 "), "{request}");
assert!(missing.starts_with("GET 404 /missing "), "{missing}");
let options = stderr.lines().find(|line| line.starts_with("OPTIONS")).unwrap();
assert!(options.starts_with("OPTIONS 200 /ready "), "{options}");
for line in [request, missing, options] {
assert_eq!(line.find('/'), Some(13), "{line}");
assert!(!line.contains("laravel::request"), "{line}");
assert!(!line.contains("status="), "{line}");
assert!(!line.contains("duration_ms="), "{line}");
assert!(!line.contains("tenant="), "{line}");
}
if ansi {
assert!(raw.contains("\x1b[38;5;117mGET \x1b[0m"), "{raw:?}");
for (status, color) in [(200, 42), (302, 75), (404, 214), (500, 204)] {
assert!(raw.contains(&format!("\x1b[38;5;{color}m{status}\x1b[0m")), "{raw:?}");
}
let request = raw
.lines()
.find(|line| line.contains(" /users/7 ") && line.starts_with('\x1b'))
.unwrap();
assert!(request.contains("\x1b[38;5;243m"), "{request:?}");
assert!(request.ends_with("\x1b[0m"), "{request:?}");
}
let request = json
.iter()
.find(|line| {
line["message"]
.as_str()
.is_some_and(|message| message.starts_with("GET /users/7 200 "))
})
.unwrap();
assert_eq!(request["request"]["method"], "GET");
assert_eq!(request["request"]["path"], "/users/7");
assert_eq!(request["request"]["route"], "/users/{user}");
assert!(request["fields"]["duration_ms"].is_number());
let request = file.lines().find(|line| line.contains("GET /users/7 200 ")).unwrap();
assert!(request.contains("laravel::request:"), "{request}");
assert!(request.contains("status=200"), "{request}");
assert!(request.contains("duration_ms="), "{request}");
} else {
for output in [stderr.as_ref(), stdout.as_str(), file.as_str()] {
assert!(!output.contains("/users/7 200"), "{output}");
assert!(!output.contains("/missing"), "{output}");
}
}
let warning = stderr
.lines()
.find(|line| line.contains("application request warning"))
.unwrap();
assert!(warning.contains("WARN"), "{warning}");
assert!(warning.contains("id="), "{warning}");
assert!(warning.contains("tenant=\"acme\""), "{warning}");
assert!(warning.contains("reason=\"the card was declined\""), "{warning}");
if !ansi {
assert!(!raw.contains('\x1b'));
}
let warning = json
.iter()
.find(|line| line["message"] == "application request warning")
.unwrap();
assert_eq!(warning["context"]["tenant"], "acme");
assert_eq!(warning["fields"]["reason"], "the card was declined");
let warning = file
.lines()
.find(|line| line.contains("application request warning"))
.unwrap();
assert!(warning.contains("tenant=\"acme\""), "{warning}");
assert!(warning.contains("reason=\"the card was declined\""), "{warning}");
assert!(!file.contains('\x1b'));
}
}
#[test]
fn piped_logs_respect_color_overrides() {
use laravel::config::logging::LogFormat;
use std::process::Command;
if let Some(root) = std::env::var_os("LARAVEL_TEST_LOG_COLORS") {
let app = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.app.base_path = root.into();
config.logging.channels = vec![LogChannel::stderr(), LogChannel::stdout(), LogChannel::daily()];
if std::env::var_os("LARAVEL_TEST_JSON_LOGS").is_some() {
config.logging.format = LogFormat::Json;
}
})
.create();
let guard = app.init_logging().unwrap();
tracing::info!("color probe");
drop(guard);
return;
}
for (force, no_color, json, colored) in [
(None, None, false, false),
(Some("1"), None, false, true),
(Some("2"), None, false, true),
(Some("3"), None, false, true),
(Some(""), None, false, true),
(Some("0"), None, false, false),
(Some("1"), Some("1"), false, false),
(Some("1"), Some(""), false, true),
(Some("1"), None, true, false),
] {
let root = TempDir::new("log-colors");
let mut command = Command::new(std::env::current_exe().unwrap());
command
.args(["--exact", "logging::piped_logs_respect_color_overrides", "--nocapture"])
.env("LARAVEL_TEST_LOG_COLORS", root.as_os_str())
.env_remove("FORCE_COLOR")
.env_remove("NO_COLOR")
.env_remove("LARAVEL_TEST_JSON_LOGS");
if let Some(value) = force {
command.env("FORCE_COLOR", value);
}
if let Some(value) = no_color {
command.env("NO_COLOR", value);
}
if json {
command.env("LARAVEL_TEST_JSON_LOGS", "1");
}
let output = command.output().unwrap();
assert!(output.status.success(), "{output:?}");
for bytes in [&output.stdout, &output.stderr] {
let output = String::from_utf8_lossy(bytes);
let line = output.lines().find(|line| line.contains("color probe")).unwrap();
assert_eq!(
line.contains('\x1b'),
colored,
"FORCE_COLOR={force:?}, NO_COLOR={no_color:?}, json={json}: {line:?}"
);
if json {
assert_eq!(serde_json::from_str::<Value>(line).unwrap()["message"], "color probe");
}
}
let file = daily_log(&root);
assert!(file.contains("color probe"));
assert!(!file.contains('\x1b'), "file logs must never contain ANSI colors");
}
}
#[test]
fn command_errors_are_reported_without_duplicate_console_logs() {
use laravel::config::logging::LogFormat;
use laravel::testing::MakesConsoleRequests;
use std::sync::atomic::{AtomicUsize, Ordering};
if let Some(root) = std::env::var_os("LARAVEL_TEST_COMMAND_ERRORS") {
let reports = Arc::new(AtomicUsize::new(0));
let count = reports.clone();
let layer = Lines::default();
let writer = layer.clone();
let app = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.app.base_path = root.into();
config.logging.channels = vec![LogChannel::stderr(), LogChannel::stdout(), LogChannel::daily()];
if std::env::var_os("LARAVEL_TEST_JSON_LOGS").is_some() {
config.logging.format = LogFormat::Json;
}
})
.with_errors(move |errors, _| {
errors.report_all(move |_| {
count.fetch_add(1, Ordering::Relaxed);
tracing::warn!("reporter diagnostic");
});
})
.with_logging(move |logging, _| {
logging.layer(tracing_subscriber::fmt::layer().json().with_writer(writer));
})
.create();
let guard = app.init_logging().unwrap();
let runtime = tokio::runtime::Runtime::new().unwrap();
runtime.block_on(async {
for flags in ["", " -q", " -vvv"] {
let result = app.command(&format!("cache:clear missing-store{flags}")).await;
result.assert_exit_code(1);
assert_eq!(result.error_output(), "cache store `missing-store` isn't defined\n");
assert!(result.output().is_empty());
}
app.scope(async || {
laravel::report(
laravel::Error::from(std::io::Error::other("the disk is full"))
.context("separate reported failure"),
);
})
.await;
});
assert_eq!(reports.load(Ordering::Relaxed), 4);
assert_eq!(
layer
.json()
.iter()
.filter(|line| line["target"] == "laravel::errors")
.count(),
4
);
drop(guard);
return;
}
for json in [false, true] {
let root = TempDir::new("command-errors");
let mut child = std::process::Command::new(std::env::current_exe().unwrap());
child
.args([
"--exact",
"logging::command_errors_are_reported_without_duplicate_console_logs",
"--nocapture",
])
.env("LARAVEL_TEST_COMMAND_ERRORS", root.as_os_str())
.env_remove("LARAVEL_TEST_JSON_LOGS");
if json {
child.env("LARAVEL_TEST_JSON_LOGS", "1");
}
let result = child.output().unwrap();
assert!(result.status.success(), "{result:?}");
for bytes in [&result.stdout, &result.stderr] {
let output = String::from_utf8_lossy(bytes);
let logged = output
.lines()
.filter(|line| line.starts_with('{') && line.contains("missing-store"))
.count();
assert_eq!(logged, if json { 3 } else { 0 }, "{output}");
if !json {
assert!(!output.contains("missing-store"), "{output}");
}
assert!(output.contains("reporter diagnostic"), "{output}");
assert!(output.contains("separate reported failure"), "{output}");
}
let output = daily_log(&root);
assert_eq!(output.matches("missing-store").count(), 3, "{output}");
assert!(!output.contains("console_rendered"), "{output}");
assert_eq!(output.matches("causes").count(), 1, "{output}");
if json {
let report: Value = output
.lines()
.map(|line| serde_json::from_str::<Value>(line).unwrap())
.find(|line| line["target"] == "laravel::errors" && line["error"]["causes"].is_array())
.unwrap_or_else(|| panic!("{output}"));
assert_eq!(
report["error"]["causes"],
serde_json::json!(["the disk is full"]),
"{report}"
);
} else {
let report = output
.lines()
.find(|line| line.contains("separate reported failure"))
.unwrap();
assert!(report.contains(r#"causes=["the disk is full"]"#), "{report}");
}
}
}
#[test]
fn a_destination_listed_twice_stops_the_application() {
let error = Application::configure()
.replace_env(Env::from_iter([("LOG_CHANNEL", "stderr,daily,stderr")]))
.try_create()
.unwrap_err();
assert_eq!(
error.to_string(),
"the `stderr` log channel is listed twice: each destination may have one channel"
);
let in_code = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.logging.channels = vec![LogChannel::daily(), LogChannel::daily().level("warn")];
})
.try_create();
assert!(in_code.is_err());
}
#[test]
fn a_log_check_every_channel_rejects_keeps_the_next_line() {
if std::env::var_os("LARAVEL_TEST_REJECTED_LOG_CHECK").is_some() {
let app = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| config.logging.channels = vec![LogChannel::stderr()])
.create();
let guard = app.init_logging().unwrap();
if log::log_enabled!(target: "sqlx::query", log::Level::Debug) {
tracing::debug!(target: "sqlx::query", "SELECT 1");
}
tracing::warn!("the line after the check");
log::warn!(target: "dependency", "a log record");
drop(guard);
return;
}
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"logging::a_log_check_every_channel_rejects_keeps_the_next_line",
"--nocapture",
])
.env("LARAVEL_TEST_REJECTED_LOG_CHECK", "1")
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("the line after the check"), "{stderr}");
assert!(stderr.contains("dependency: a log record"), "{stderr}");
}
#[test]
fn a_log_logger_installed_first_keeps_the_application_logs() {
struct Silent;
impl log::Log for Silent {
fn enabled(&self, _: &log::Metadata<'_>) -> bool {
true
}
fn log(&self, _: &log::Record<'_>) {}
fn flush(&self) {}
}
if std::env::var_os("LARAVEL_TEST_LOG_LOGGER_FIRST").is_some() {
log::set_logger(&Silent).unwrap();
let app = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| config.logging.channels = vec![LogChannel::stderr()])
.create();
let guard = app
.init_logging()
.expect("installs the tracing logger beside the `log` logger");
tracing::warn!("a line after the `log` logger");
drop(guard);
return;
}
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"logging::a_log_logger_installed_first_keeps_the_application_logs",
"--nocapture",
])
.env("LARAVEL_TEST_LOG_LOGGER_FIRST", "1")
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("a line after the `log` logger"), "{stderr}");
}
#[test]
fn laravel_cloud_socket_sends_json_lines_for_requests_and_failed_commands() {
use std::io::{BufRead, BufReader};
use std::net::TcpListener;
use laravel::testing::MakesConsoleRequests;
if let Some(socket) = std::env::var_os("LARAVEL_TEST_CLOUD_SOCKET") {
let socket = socket.to_string_lossy().into_owned();
let app = Application::configure()
.replace_env(Env::from_iter([
("LOG_CHANNEL", "laravel-cloud-socket"),
("LOG_FORMAT", "text"),
("LARAVEL_CLOUD_LOG_SOCKET", socket.as_str()),
]))
.with_routing(|routing, _| {
routing.routes(|route: &mut Router| {
route.post("/orders/{order}", || async {
laravel::context::add("tenant", "acme");
tracing::info!(order_id = 7, "charging order");
Err::<&str, laravel::Error>(
laravel::Error::from(std::io::Error::other("gateway timed out")).context("charge failed"),
)
});
});
})
.create();
let guard = app.init_logging().unwrap();
tokio::runtime::Runtime::new().unwrap().block_on(async {
app.post("/orders/7")
.header("Cloud-Request-ID", "0197d1b0-7e5c-7a1f-9c43-2b6f0e8d4a11")
.await
.assert_internal_server_error();
app.command("cache:clear missing-store").await.assert_exit_code(1);
});
drop(guard);
return;
}
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let socket = format!("tcp://{}", listener.local_addr().unwrap());
let received = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
BufReader::new(stream)
.lines()
.map(|line| serde_json::from_str::<Value>(&line.unwrap()).unwrap())
.collect::<Vec<_>>()
});
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"logging::laravel_cloud_socket_sends_json_lines_for_requests_and_failed_commands",
"--nocapture",
])
.env("LARAVEL_TEST_CLOUD_SOCKET", &socket)
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
let lines = received.join().unwrap();
let info = lines
.iter()
.find(|line| line["message"] == "charging order")
.unwrap_or_else(|| panic!("missing info line: {lines:#?}"));
assert!(info["time"].as_str().is_some_and(|time| time.ends_with('Z')), "{info}");
assert_eq!(info["level"], "info");
assert_eq!(info["fields"], serde_json::json!({ "order_id": 7 }));
assert_eq!(info["context"], serde_json::json!({ "tenant": "acme" }));
assert_eq!(
info["request"]["cloud_request_id"],
"0197d1b0-7e5c-7a1f-9c43-2b6f0e8d4a11"
);
assert_eq!(info["request"]["method"], "POST");
assert_eq!(info["request"]["path"], "/orders/7");
assert_eq!(info["request"]["route"], "/orders/{order}");
assert!(info["request"]["id"].is_string(), "{info}");
let request_error = lines
.iter()
.find(|line| line["target"] == "laravel::errors" && line.get("request").is_some())
.unwrap_or_else(|| panic!("missing request error line: {lines:#?}"));
assert_eq!(request_error["level"], "error");
assert_eq!(request_error["message"], "charge failed: gateway timed out");
assert_eq!(request_error["error"]["type"], std::any::type_name::<std::io::Error>());
assert!(request_error["error"]["location"].is_string(), "{request_error}");
assert_eq!(
request_error["error"]["causes"],
serde_json::json!(["gateway timed out"])
);
assert_eq!(
request_error["request"]["cloud_request_id"],
"0197d1b0-7e5c-7a1f-9c43-2b6f0e8d4a11"
);
assert_eq!(request_error["context"], serde_json::json!({ "tenant": "acme" }));
let command_error = lines
.iter()
.find(|line| line["target"] == "laravel::errors" && line.get("command").is_some())
.unwrap_or_else(|| panic!("missing command error line: {lines:#?}"));
assert_eq!(command_error["level"], "error");
assert_eq!(command_error["message"], "cache store `missing-store` isn't defined");
assert_eq!(command_error["command"], serde_json::json!({ "name": "cache:clear" }));
assert!(command_error["error"]["type"].is_string(), "{command_error}");
}
#[derive(laravel::queue::Queueable)]
struct ShipOrder;
#[laravel::workflow::workflow(name = "orders.ship")]
impl ShipOrder {
async fn handle(self, run: &laravel::workflow::Run) -> laravel::Result<()> {
run.step("print label", async {
tracing::warn!("label printed");
Ok(())
})
.await
}
}
#[tokio::test]
async fn a_sent_mails_line_is_in_its_send_span() {
let (lines, _guard) = Lines::capture();
let app = app(Env::default());
app.scope(async || {
laravel::mail::to("taylor@laravel.com")
.send(laravel::mail::Message::new().subject("Receipt").text("Paid"))
.await
})
.await
.unwrap();
let sent = lines.find("Mail sent");
assert_eq!(sent["span"]["otel.name"], "mail.send", "{sent}");
}