Os.stderr
func Os.stderr(): File.HandleOs.stderr returns the program's standard error, which eprint and eprintln write to as well.
Details
- The handle is not buffered, so each write reaches standard error at once, in order with what eprint, eprintln and standard output write.
- Unlike
eprintln, theFilefunctions on the handle return aResult, so a failed write is anErrthe program can see. A write whose reader has gone, a broken pipe, ends the program as SIGPIPE does, and a shell reports status 141. Only on Windows, or under a host that gives the program its own writer, is it anErr. - File.close on the handle does nothing and is
Ok; standard error stays open.
Basic examples
Write a line to standard error. Standard output holds only what println writes:
println("total: 42")
try File.writeLine(Os.stderr(), "warning: 3 rows skipped")total: 42Call the File functions on the handle through .:
let err = Os.stderr()
try err.writeText("checking... ")
try err.writeLine("done")Scope
Text, lines, and bytes
File.writeText writes text as it is, File.writeLine adds a newline, and File.writeChunk writes bytes:
let err = Os.stderr()
try err.writeText("no newline")
try err.writeChunk("\n".toBytes())
try err.writeLine("one line")Standard error then holds:
no newline
one lineA handle like any other
A function that writes to a File.Handle writes to standard error, standard output, or a file alike:
func report(out: File.Handle, failed: int): Result[void, Error] {
out.writeLine("${failed} checks failed")
}
try report(Os.stdout(), 0)
try report(Os.stderr(), 2)0 checks failedBuffered
File.buffered collects many small writes and writes them out at File.flush:
let log = File.buffered(Os.stderr())
for i in Iter.range(0, 1000) {
try log.writeLine("step ${i}")
}
try log.flush()Applications
Route messages by level
An if expression picks the stream, so errors go to standard error and the rest to standard output:
func log(level: string, msg: string): Result[void, Error] {
let out = if level == "info" { Os.stdout() } else { Os.stderr() }
out.writeLine("[${level}] ${msg}")
}
try log("info", "server started")
try log("error", "port 8080 in use")[info] server startedColor only on a terminal
File.isTerminal tells whether a person reads standard error, so escape codes stay out of a log file:
let label = if Os.stderr().isTerminal() { "\u{1b}[31merror\u{1b}[0m" } else { "error" }
try Os.stderr().writeLine("${label}: config not found")Merge a child's error output
A command started with Cmd.start writes to the program's standard error by default. Pass stderr: Os.stdout() to merge both outputs, as 2>&1 does in a shell:
let c = Cmd.new("sh", ["-c", "echo out; echo err >&2"])
let p = try c.start(stderr: Os.stdout())
let status = try p.wait()
println("status ${status}")out
err
status 0Properties and relations
Closing standard error and flushing it both do nothing and are Ok, and the stream stays open:
assert(File.close(Os.stderr()) is Ok)
assert(File.flush(Os.stderr()) is Ok)
assert(Os.stderr().writeLine("still open") is Ok)Possible issues
Os.stderr is a function
Call it to get the handle; the function itself is not a File.Handle:
let r = File.writeLine(Os.stderr, "oops")
// error: cannot use func(): File.Handle where File.Handle is expectedThe File functions take text
File.writeLine takes a string, while eprintln takes any value. Interpolate a value to write it:
let r = File.writeLine(Os.stderr(), 42) // error: cannot use int where string is expectedlet count = 42
try Os.stderr().writeLine("${count}")A dropped Result hides a failed write
A write called as a statement compiles, and its Result is dropped with any error in it, so ant check warns about it. Use try when the write matters, _ = to drop the Result on purpose, or eprintln when it does not matter:
Os.stderr().writeLine("ignored if it fails")
// warning: the Result of writeLine is discarded, so its Err is lost
_ = Os.stderr().writeLine("dropped on purpose")
try Os.stderr().writeLine("checked")An unflushed buffer is lost
A buffered handle writes only when full, at File.flush and at File.close. What it holds when the run ends is lost, so close it at the end:
let log = File.buffered(Os.stderr())
try log.writeLine("finished")
try log.close()eprintln goes past a buffered handle
eprint, eprintln and writes to Os.stderr() itself go past the buffer of File.buffered(Os.stderr()), so they can come out before what the buffer holds:
let log = File.buffered(Os.stderr())
try log.writeLine("buffered")
eprintln("direct")
try log.flush()Standard error then holds direct before buffered:
direct
bufferedFlush the buffered handle before writing to the stream directly, or write everything through the buffered handle.
See also
eprintln, eprint, Os.stdout, Os.stdin, File.writeLine, File.buffered, File.isTerminal, Cmd.start
