2019-12-27 11:55:15 -03:00
|
|
|
package logext
|
|
|
|
|
2021-07-23 08:09:29 -03:00
|
|
|
import (
|
|
|
|
"io"
|
2022-06-21 21:11:15 -03:00
|
|
|
"os"
|
2019-12-27 11:55:15 -03:00
|
|
|
|
2022-06-21 21:11:15 -03:00
|
|
|
"github.com/caarlos0/log"
|
2021-07-23 08:09:29 -03:00
|
|
|
)
|
|
|
|
|
2020-05-26 00:48:10 -03:00
|
|
|
// NewWriter creates a new log writer.
|
2023-02-01 23:25:36 -03:00
|
|
|
func NewWriter() io.Writer {
|
|
|
|
return NewConditionalWriter(false)
|
2021-12-06 10:07:47 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewConditionalWriter creates a new log writer that only writes when the given condition is met or debug is enabled.
|
2023-02-01 23:25:36 -03:00
|
|
|
func NewConditionalWriter(condition bool) io.Writer {
|
2021-12-06 10:07:47 -03:00
|
|
|
if condition || isDebug() {
|
2023-02-01 23:25:36 -03:00
|
|
|
logger, ok := log.Log.(*log.Logger)
|
|
|
|
if !ok {
|
|
|
|
return os.Stderr
|
2021-07-23 08:09:29 -03:00
|
|
|
}
|
2023-02-01 23:25:36 -03:00
|
|
|
return logger.Writer
|
2021-07-23 08:09:29 -03:00
|
|
|
}
|
|
|
|
return io.Discard
|
|
|
|
}
|
|
|
|
|
|
|
|
func isDebug() bool {
|
|
|
|
return logLevel() == log.DebugLevel
|
2020-05-10 17:03:49 +01:00
|
|
|
}
|
|
|
|
|
2021-07-23 08:09:29 -03:00
|
|
|
func logLevel() log.Level {
|
|
|
|
if logger, ok := log.Log.(*log.Logger); ok {
|
|
|
|
return logger.Level
|
|
|
|
}
|
|
|
|
return log.InfoLevel
|
|
|
|
}
|