How to Print Message to Stderr in Go

How can I print to Stderr in Go without using log

The Go builtin functions print and println print to stderr. So if you simply want to output some text to stderr you can do

package main

func main() {
println("Hello stderr!")
}

Documentation: https://golang.org/pkg/builtin/#print

How do I print message to stderr in Go?

The log package by default prints to os.Stderr.

You can also use os.Stderr directly (it's an os.File).

How to process stderr in go?

StderrPipe returns a ReadCloser. You can use that to create a bufio.Scanner and then read lines one by one:

sc := bufio.NewScanner(stderr)
for sc.Scan() {
fmt.Printf("Line: %s\n", sc.Text());
}

Does fmt.Print() write to stdout in GoLang?

From the documentation:

Print formats using the default formats for its operands and writes to standard output.

So yep, it writes to stdout.

How I can print to stderr in C?

The syntax is almost the same as printf. With printf you give the string format and its contents ie:

printf("my %s has %d chars\n", "string format", 30);

With fprintf it is the same, except now you are also specifying the place to print to:

FILE *myFile;
...
fprintf( myFile, "my %s has %d chars\n", "string format", 30);

Or in your case:

fprintf( stderr, "my %s has %d chars\n", "string format", 30);

Catch stdErr output in golang

As the comment by @tkausi suggests, you ought to set a custom logger for the go-sql-driver package with https://godoc.org/github.com/go-sql-driver/mysql#SetLogger

Your custom logger can then do whatever makes sense for your application, including "swallowing" these logging statements and not displaying anything in case of no errors.


To answer the question's title, you can capture os.Stderr with something like this:

func doPrint() {
fmt.Fprintf(os.Stderr, "output")
}

func main() {
old := os.Stderr
r, w, _ := os.Pipe()
os.Stderr = w

doPrint()

w.Close()
var buf bytes.Buffer
io.Copy(&buf, r)
os.Stderr = old

fmt.Println("Captured:", buf.String())
}

Bash command that prints a message on stderr

echo something >&2 is the correct way to do what you want.

However...

This will create a little program that will echo its arguments to stderr:

gcc -o echoerr -x c - <<'EOF'
#include <stdio.h>
#include <stdlib.h>
void main(int argc, char **argv) {
int i;
for (i = 1; i < argc; i++) {
fprintf(stderr, "%s ", argv[i]);
}
fprintf(stderr, "\n");
exit(0);
}
EOF

You can use it like this:

$ ./echoerr this is an error message
this is an error message
$ ./echoerr this is an error message 2>error.out
$ cat error.out
this is an error message


Related Topics



Leave a reply



Submit