From 6cd8d684fda8caaa8d1fb8fa4b23b844850f4e7b Mon Sep 17 00:00:00 2001 From: Edward Muller Date: Thu, 5 Sep 2019 19:34:46 -0700 Subject: [PATCH] some minimal documentation for Logger.Writer{,Level} This also includes two examples extracted from the readme. --- writer.go | 6 ++++++ writer_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 writer_test.go diff --git a/writer.go b/writer.go index 9e1f751..72e8e3a 100644 --- a/writer.go +++ b/writer.go @@ -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) } diff --git a/writer_test.go b/writer_test.go new file mode 100644 index 0000000..5c34927 --- /dev/null +++ b/writer_test.go @@ -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()) +}