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.
Code
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.txtWhat 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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.