Skip to content

Commit

Permalink
Merge pull request #33 from hashicorp/f-expose-writer
Browse files Browse the repository at this point in the history
Expose Writer to allow for configuring standard logger
  • Loading branch information
blalor authored Feb 14, 2019
2 parents 4783cae + b6eaa06 commit 90f2fbc
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 2 deletions.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,21 @@ stdLogger.Printf("[DEBUG] %+v", stdLogger)
... [DEBUG] my-app: &{mu:{state:0 sema:0} prefix: flag:0 out:0xc42000a0a0 buf:[]}
```

Alternatively, you may configure the system-wide logger:

```go
// log the standard logger from 'import "log"'
log.SetOutput(appLogger.Writer(&hclog.StandardLoggerOptions{InferLevels: true}))
log.SetPrefix("")
log.SetFlags(0)

log.Printf("[DEBUG] %d", 42)
```

```text
... [DEBUG] my-app: 42
```

Notice that if `appLogger` is initialized with the `INFO` log level _and_ you
specify `InferLevels: true`, you will not see any output here. You must change
`appLogger` to `DEBUG` to see output. See the docs for more information.
7 changes: 6 additions & 1 deletion int.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding"
"encoding/json"
"fmt"
"io"
"log"
"os"
"reflect"
Expand Down Expand Up @@ -503,5 +504,9 @@ func (z *intLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger {
opts = &StandardLoggerOptions{}
}

return log.New(&stdlogAdapter{z, opts.InferLevels}, "", 0)
return log.New(z.StandardWriter(opts), "", 0)
}

func (z *intLogger) StandardWriter(opts *StandardLoggerOptions) io.Writer {
return &stdlogAdapter{z, opts.InferLevels}
}
3 changes: 3 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,9 @@ type Logger interface {

// Return a value that conforms to the stdlib log.Logger interface
StandardLogger(opts *StandardLoggerOptions) *log.Logger

// Return a value that conforms to io.Writer, which can be passed into log.SetOutput()
StandardWriter(opts *StandardLoggerOptions) io.Writer
}

type StandardLoggerOptions struct {
Expand Down
7 changes: 6 additions & 1 deletion nulllogger.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package hclog

import (
"io"
"io/ioutil"
"log"
)
Expand Down Expand Up @@ -43,5 +44,9 @@ func (l *nullLogger) ResetNamed(name string) Logger { return l }
func (l *nullLogger) SetLevel(level Level) {}

func (l *nullLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger {
return log.New(ioutil.Discard, "", log.LstdFlags)
return log.New(l.StandardWriter(opts), "", log.LstdFlags)
}

func (l *nullLogger) StandardWriter(opts *StandardLoggerOptions) io.Writer {
return ioutil.Discard
}

0 comments on commit 90f2fbc

Please sign in to comment.