Stderr Diagnostics Leave Stdout For Data

Keep records on stdout and warnings on a locked io::stderr handle so redirection stays clean and diagnostics never corrupt the data stream.

RustCli Tooling

Code

rustsnippet
16 lines
use std::io::{self, Write};

fn main() {
    let stderr = io::stderr();
    let mut handle = stderr.lock();

    println!("record,1");
    println!("record,2");

    // 数据走 stdout,诊断 diagnostics 走 stderr:重定向互不污染
    writeln!(handle, "warn: skipped malformed line").ok();
    writeln!(handle, "info: 2 records emitted").ok();
    handle.flush().ok();

    // 简单场景也可以直接用 eprintln!,批量输出才需要锁定的 handle
}

What the snippet does

Read it one way: the function main, doing all the work.

Caveats

  • Dependencies number zero; the language runtime covers every call.

Using it

The signature that matters reads fn main()

The file’s steps are announced in the output: record,1, record,2.

Key statements

writeln!(handle, "warn: skipped malformed line").ok();
writeln!(handle, "info: 2 records emitted").ok();
let mut handle = stderr.lock();

Interactive Tools for This Topic

FAQ

What does Stderr Diagnostics Leave Stdout For Data print when run?
The script runs standalone; its 2 labeled outputs include `record,1`, `record,2`.