Diagnostics On Stderr Keep Stdout Clean

Send progress and warnings to os.Stderr while result rows stay on stdout, so redirection and pipes capture clean data only.

GoCli Tooling

Code

gosnippet
25 lines
package main

import (
	"fmt"
	"log"
	"os"
)

// diagnostics(诊断/进度)只写 stderr,stdout 留给结果数据
func logProgress(msg string) {
	fmt.Fprintf(os.Stderr, "[progress] %s\n", msg)
}

func main() {
	logger := log.New(os.Stderr, "warn: ", log.Lmsgprefix)

	logProgress("scanning 3 files")

	fmt.Println("line 1: alpha")
	fmt.Println("line 2: beta")
	logger.Println("1 file skipped (empty)")

	logProgress("done")
}
// go run . > out.txt 2> err.txt:out.txt 只有结果行,进度与告警全在 err.txt

What the code does

The moving parts are the functions logProgress and main.

Points of care

  • No install step: all APIs used ship with the platform.

Applying it

The main signature reads func logProgress(msg string)

Each run prints the 2 labeled blocks line 1: alpha, line 2: beta in source order.

main sequences logProgress; executing the file runs that flow once.

Statements that matter

func logProgress(msg string) {
fmt.Fprintf(os.Stderr, "[progress] %s\n", msg)
}
func main() {
logger := log.New(os.Stderr, "warn: ", log.Lmsgprefix)
logProgress("scanning 3 files")
fmt.Println("line 1: alpha")
fmt.Println("line 2: beta")
logger.Println("1 file skipped (empty)")
logProgress("done")
}

Interactive Tools for This Topic

FAQ

What does Diagnostics On Stderr Keep Stdout Clean print when run?
No setup needed: run the file and look for labeled lines like `line 1: alpha`, `line 2: beta` in the output.