some minimal documentation for Logger.Writer{,Level}

This also includes two examples extracted from the readme.
This commit is contained in:
Edward Muller 2019-09-05 19:34:46 -07:00
parent de736cf91b
commit 6cd8d684fd
No known key found for this signature in database
GPG Key ID: FC5833DB021899A5
2 changed files with 40 additions and 0 deletions

View File

@ -6,10 +6,16 @@ import (
"runtime"
)
// Writer at INFO level. See WriterLevel for details.
func (logger *Logger) Writer() *io.PipeWriter {
return logger.WriterLevel(InfoLevel)
}
// WriterLevel returns an io.Writer that can be used to write arbitrary text to
// the logger at the given log level. Each line written to the writer will be
// printed in the usual way using formatters and hooks. The writer is part of an
// io.Pipe and it is the callers responsibility to close the writer when done.
// This can be used to override the standard library logger easily.
func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
return NewEntry(logger).WriterLevel(level)
}

34
writer_test.go Normal file
View File

@ -0,0 +1,34 @@
package logrus_test
import (
"log"
"net/http"
"github.com/sirupsen/logrus"
)
func ExampleLogger_Writer_httpServer() {
logger := logrus.New()
w := logger.Writer()
defer w.Close()
srv := http.Server{
// create a stdlib log.Logger that writes to
// logrus.Logger.
ErrorLog: log.New(w, "", 0),
}
if err := srv.ListenAndServe(); err != nil {
logger.Fatal(err)
}
}
func ExampleLogger_Writer_stdlib() {
logger := logrus.New()
logger.Formatter = &logrus.JSONFormatter{}
// Use logrus for standard log output
// Note that `log` here references stdlib's log
// Not logrus imported under the name `log`.
log.SetOutput(logger.Writer())
}