Rust Playbook

Course › Week 4 · Async and plugging into Laravel › Day 4 · lesson 25 of 42 · 25 min reading + 45 min practice

Config and logging

Read .env, log with tracing, and exit codes PHP can understand.

dotenvytracingexit codes

On this page
  1. 1. Config: read once, check everything, fail at startup
  2. 2. tracing: logs with levels and fields
  3. 3. RUST_LOG: choose the level when you run it
  4. 4. Spans: context for everything inside
  5. 5. JSON logs for machines
  6. 6. stdout is for data, stderr is for people
  7. 7. Exit codes: how a process says what happened
  8. Coming from PHP
  9. Practice
  10. Remember

Three small things that decide whether a tool can run in production next to Laravel. Where its settings come from, what it tells you while it runs, and how it says “done”, “failed” or “partly done” in a way a PHP process can read.

Laravel solves the same problems with .env and config(), Log::info(), and Artisan’s exit codes. Each section maps one onto the Rust tool.

1. Config: read once, check everything, fail at startup

The worker’s settings are a struct, built once in main from environment variables. Every value is checked there: a missing database URL or a concurrency of lots stops the program with one sentence before it touches anything, instead of failing halfway through a batch.

dotenvy::dotenv() loads a .env file into the environment if there is one, the same KEY=value format as Laravel’s. A real environment variable wins over the file, which is also how Laravel behaves. error.not_found() tells “no .env file” (fine) from “a broken .env file” (not fine).

src/main.rs
use std::env;
use std::process::ExitCode;

use thiserror::Error;

/// Everything the worker needs from its environment, checked once at startup.
struct Config {
    database_url: String,
    analysis_url: String,
    concurrency: usize,
}

#[derive(Debug, Error)]
enum ConfigError {
    #[error("{0} is not set")]
    Missing(&'static str),

    #[error("{name} must be a whole number from 1 to 64, got '{value}'")]
    Invalid { name: &'static str, value: String },

    #[error("cannot read .env: {0}")]
    DotEnv(#[from] dotenvy::Error),
}

impl Config {
    fn from_env() -> Result<Config, ConfigError> {
        // .env is optional, like in production; a .env that exists but is broken is an error.
        match dotenvy::dotenv() {
            Ok(_) => {}
            Err(error) if error.not_found() => {}
            Err(error) => return Err(error.into()),
        }

        let database_url = required("DATABASE_URL")?;
        let analysis_url = env::var("ANALYSIS_URL")
            .unwrap_or_else(|_| String::from("http://127.0.0.1:8000/api/analyse"));
        let concurrency = match env::var("WORKER_CONCURRENCY") {
            Err(_) => 8,
            Ok(value) => match value.trim().parse::<usize>() {
                Ok(n) if (1..=64).contains(&n) => n,
                _ => {
                    return Err(ConfigError::Invalid {
                        name: "WORKER_CONCURRENCY",
                        value,
                    });
                }
            },
        };
        Ok(Config {
            database_url,
            analysis_url,
            concurrency,
        })
    }
}

fn required(name: &'static str) -> Result<String, ConfigError> {
    match env::var(name) {
        Ok(value) if !value.trim().is_empty() => Ok(value),
        _ => Err(ConfigError::Missing(name)),
    }
}

fn main() -> ExitCode {
    let config = match Config::from_env() {
        Ok(config) => config,
        Err(error) => {
            eprintln!("worker: {error}");
            return ExitCode::FAILURE;
        }
    };
    let host = config.database_url.split('@').next_back().unwrap_or("?");
    println!("database: …@{host}");
    println!("analysis: {}", config.analysis_url);
    println!("concurrency: {}", config.concurrency);
    ExitCode::SUCCESS
}
$ cargo run
database: …@db.internal:5432/nordic
analysis: http://127.0.0.1:8000/api/analyse
concurrency: 16

.next_back() takes the last piece of the split, so the password before the @ is never printed. Logging a database URL with its password is a classic leak.

Laravel’s advice “only call env() inside config files” is the same idea as this struct: read the environment in one place, use typed values everywhere else.

$ cargo run
worker: DATABASE_URL is not set
exit code 1

No .env and no DATABASE_URL: one sentence, exit code 1.

$ cargo run
worker: WORKER_CONCURRENCY must be a whole number from 1 to 64, got 'lots'
exit code 1

A value that is there but wrong is just as clear.

2. tracing: logs with levels and fields

println! is for output; logs need levels, a destination you choose, and context. The tracing crate gives macros for each level (error!, warn!, info!, debug!, trace!), and fields written as name = value before the message, like Laravel’s context array.

Nothing is printed until a subscriber is installed: tracing_subscriber::fmt() writes readable lines. with_writer(io::stderr) sends them to stderr (section 5 explains why). Timestamps are on by default; the examples here turn them off with without_time() so the output on the page is stable.

src/main.rs
use std::io;

use tracing::{error, info, warn};

fn main() {
    tracing_subscriber::fmt()
        .with_writer(io::stderr)
        .without_time()
        .init();

    info!(batch = 7, evaluations = 250, "batch started");
    warn!(
        evaluation_id = 1042,
        attempt = 2,
        "analysis API slow, retrying"
    );
    error!(
        evaluation_id = 1077,
        reason = "no answers",
        "evaluation skipped"
    );
    info!(batch = 7, written = 249, skipped = 1, "batch finished");
}
$ cargo run
 INFO hello: batch started batch=7 evaluations=250
 WARN hello: analysis API slow, retrying evaluation_id=1042 attempt=2
ERROR hello: evaluation skipped evaluation_id=1077 reason="no answers"
 INFO hello: batch finished batch=7 written=249 skipped=1

Fields stay separate from the message, so a log search can filter on evaluation_id=1042 without parsing sentences. reason = "no answers" shows a string field; %value and ?value before a field use its Display or Debug form.

3. RUST_LOG: choose the level when you run it

An EnvFilter reads the level from the RUST_LOG environment variable, so the same binary can be quiet in production and detailed while you debug, like LOG_LEVEL in Laravel. The default here is info; RUST_LOG=debug shows more, and RUST_LOG=worker=debug,sqlx=warn sets it per crate.

src/main.rs
use std::io;

use tracing::{debug, info};
use tracing_subscriber::EnvFilter;

fn main() {
    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(io::stderr)
        .without_time()
        .init();

    info!(batch = 7, "batch started");
    debug!(
        sql = "select … from answers where evaluation_id = any($1)",
        ids = 250,
        "loading answers"
    );
    info!(batch = 7, "batch finished");
}
$ cargo run
 INFO worker: batch started batch=7
 INFO worker: batch finished batch=7

With no RUST_LOG, the debug! line is filtered out. The same program with RUST_LOG=debug:

$ cargo run
 INFO worker: batch started batch=7
DEBUG worker: loading answers sql="select … from answers where evaluation_id = any($1)" ids=250
 INFO worker: batch finished batch=7

Each line names where it came from, worker, the crate. That is what RUST_LOG=worker=debug filters on.

4. Spans: context for everything inside

#[tracing::instrument] on a function opens a span each time it is called: every log line inside carries the function’s name and arguments, without repeating them in each info!. skip(…) leaves out arguments that should not be logged, here the list of comments.

src/main.rs
use std::io;

use tracing::{info, instrument, warn};

#[instrument(skip(comments))]
fn analyse(evaluation_id: u64, comments: &[&str]) -> usize {
    info!(comments = comments.len(), "analysing");
    let empty = comments.iter().filter(|c| c.trim().is_empty()).count();
    if empty > 0 {
        warn!(empty, "some comments are empty");
    }
    comments.len() - empty
}

fn main() {
    tracing_subscriber::fmt()
        .with_writer(io::stderr)
        .without_time()
        .init();

    let kept = analyse(1042, &["Clear explanations", "", "Too fast"]);
    info!(kept, "done");
}
$ cargo run
 INFO analyse{evaluation_id=1042}: worker: analysing comments=3
 WARN analyse{evaluation_id=1042}: worker: some comments are empty empty=1
 INFO worker: done kept=2

warn!(empty, …) is short for empty = empty. In a worker that processes 250 evaluations at once, the span is what tells you which evaluation a warning belongs to.

5. JSON logs for machines

When logs go to a collector (CloudWatch, Datadog, Loki, or Laravel reading them back), one JSON object per line is easier to search than text. One method switches the format; the json feature of tracing-subscriber provides it:

src/main.rs
use std::io;

use tracing::{info, warn};

fn main() {
    tracing_subscriber::fmt()
        .json()
        .with_writer(io::stderr)
        .without_time()
        .init();

    info!(batch = 7, evaluations = 250, "batch started");
    warn!(
        evaluation_id = 1042,
        attempt = 2,
        "analysis API slow, retrying"
    );
}
$ cargo run
{"level":"INFO","fields":{"message":"batch started","batch":7,"evaluations":250},"target":"worker"}
{"level":"WARN","fields":{"message":"analysis API slow, retrying","evaluation_id":1042,"attempt":2},"target":"worker"}

A common setup: text when a person runs the tool, JSON when it runs in production, chosen by an environment variable such as LOG_FORMAT=json, read in the Config from section 1.

6. stdout is for data, stderr is for people

A program has two output streams, and a tool that another program calls must keep them apart. stdout carries the result: the JSON a Laravel job will json_decode. stderr carries everything else: logs, warnings, progress. One stray println!("starting…") in front of the JSON and the PHP side cannot parse the output.

Goes to stdoutGoes to stderr
The result PHP reads (one JSON document)Every log line, at every level
Nothing else, everError messages, the summary line, progress

This is why every logging example today used with_writer(io::stderr), and why csv2json printed its summary with eprintln!. The next lesson relies on it.

One more thing when a program reads your stderr: tracing_subscriber::fmt() writes terminal colour codes even when stderr is not a terminal. In a terminal they are colours; captured by Laravel and written to laravel.log, they are junk like . A tool meant to be called by another program uses .with_ansi(false), or JSON, which has none. (The outputs on this page are shown without them.)

7. Exit codes: how a process says what happened

Laravel’s Process and any shell script read the exit code first. Zero means success; anything else is a failure, and the specific number can say which kind. Decide your codes once, write them in the README, and never reuse one for two meanings:

CodeMeaning in this courseThe PHP side should
0Everything was processedRead the result from stdout
1The run failed: config, database, a fileFail the job; the message is on stderr; retry later
2Wrong usage (clap’s own code)Fix the command line: retrying will not help
3Partly done: some items failed, the rest were savedRead the result, report the failed items, do not retry the whole batch
101A panic: a bug in the toolFail loudly and alert; this should never happen
src/main.rs
use std::process::ExitCode;

/// What a run achieved, decided by the program's own logic.
enum Outcome {
    Done,
    Partial { failed: u32 },
}

fn exit_code(outcome: &Outcome) -> ExitCode {
    match outcome {
        Outcome::Done => ExitCode::SUCCESS,
        Outcome::Partial { .. } => ExitCode::from(3),
    }
}

fn main() -> ExitCode {
    let failed: u32 = 2; // in the worker: counted while processing
    let outcome = if failed == 0 {
        Outcome::Done
    } else {
        Outcome::Partial { failed }
    };
    if let Outcome::Partial { failed } = &outcome {
        eprintln!("worker: {failed} evaluations failed, the rest were saved");
    }
    exit_code(&outcome)
}
$ cargo run
worker: 2 evaluations failed, the rest were saved
exit code 3

Outcome::Partial { .. } matches the variant and ignores its fields. Keeping the outcome as an enum, and the code in one function, means the exit codes cannot drift apart across the program.

Coming from PHP

The Laravel side of each section:

equivalents.php
<?php

use Illuminate\Support\Facades\Log;

// 1. config: env() in config/worker.php, config('worker.concurrency') everywhere else
$concurrency = (int) config('worker.concurrency', 8);   // "lots" silently becomes 0

// 2-5. a log line with context, the same idea as tracing's fields
Log::warning('analysis API slow, retrying', ['evaluation_id' => 1042, 'attempt' => 2]);

// 7. an artisan command's exit code
return 3;   // in handle(): Command::SUCCESS is 0, FAILURE is 1

The one real difference is section 1: (int) "lots" is 0 in PHP, and a worker started with a concurrency of 0 does nothing, quietly. Validating config at startup is possible in Laravel too, but nothing pushes you to; in the Rust version, an unchecked value has no type to go into.

PracticeThe tracing docs, and a log format switch

Skim the tracing front page, sections “Spans” and “Events”, and the fmt subscriber.

Exercise: LOG_FORMAT

Read LOG_FORMAT (text or json, default text) and install the matching subscriber, both with RUST_LOG filtering and stderr output. An unknown value is a config error, not a silent fallback.

Show the solution
src/main.rs
use std::env;
use std::io;
use std::process::ExitCode;

use tracing::info;
use tracing_subscriber::EnvFilter;

fn init_logging() -> Result<(), String> {
    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
    let builder = tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(io::stderr)
        .without_time();
    match env::var("LOG_FORMAT").as_deref() {
        Err(_) | Ok("text") => builder.init(),
        Ok("json") => builder.json().init(),
        Ok(other) => return Err(format!("LOG_FORMAT must be text or json, got '{other}'")),
    }
    Ok(())
}

fn main() -> ExitCode {
    if let Err(message) = init_logging() {
        eprintln!("worker: {message}");
        return ExitCode::FAILURE;
    }
    info!(batch = 7, "batch started");
    ExitCode::SUCCESS
}
$ cargo run
{"level":"INFO","fields":{"message":"batch started","batch":7},"target":"worker"}

env::var(…).as_deref() turns Result<String, _> into Result<&str, _>, so the match can compare against string literals. The builder is only .init()-ed in one arm each, because .json() changes its type.

Remember

  • Read and check all config once at startup; fail before touching anything.
  • Logs go to stderr without colour codes when another program reads them; stdout carries only the result.

Tomorrow: calling the Rust binary from Laravel with Process, JSON over stdin and stdout, and every failure handled on the PHP side.