Fix colours on console when logging to file (#1846)

* Fix colours on console when logging to file
This commit is contained in:
WithoutPants 2021-10-15 10:38:32 +11:00 committed by GitHub
parent 1152e1acac
commit 3d5ee16e90
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 49 additions and 6 deletions

25
pkg/logger/hook.go Normal file
View File

@ -0,0 +1,25 @@
package logger
import (
"io"
"github.com/sirupsen/logrus"
)
type fileLogHook struct {
Writer io.Writer
Formatter logrus.Formatter
}
func (hook *fileLogHook) Fire(entry *logrus.Entry) error {
line, err := hook.Formatter.Format(entry)
if err != nil {
return err
}
_, err = hook.Writer.Write(line)
return err
}
func (hook *fileLogHook) Levels() []logrus.Level {
return logrus.AllLevels
}

View File

@ -2,7 +2,6 @@ package logger
import (
"fmt"
"io"
"os"
"sync"
"time"
@ -35,6 +34,13 @@ func Init(logFile string, logOut bool, logLevel string) {
customFormatter.FullTimestamp = true
logger.SetFormatter(customFormatter)
// #1837 - trigger the console to use color-mode since it won't be
// otherwise triggered until the first log entry
// this is covers the situation where the logger is only logging to file
// and therefore does not trigger the console color-mode - resulting in
// the access log colouring not being applied
_, _ = customFormatter.Format(logrus.NewEntry(logger))
if logFile != "" {
var err error
file, err = os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
@ -44,11 +50,22 @@ func Init(logFile string, logOut bool, logLevel string) {
}
}
if file != nil && logOut {
mw := io.MultiWriter(os.Stderr, file)
logger.Out = mw
} else if file != nil {
logger.Out = file
if file != nil {
if logOut {
// log to file separately disabling colours
fileFormatter := new(logrus.TextFormatter)
fileFormatter.TimestampFormat = customFormatter.TimestampFormat
fileFormatter.FullTimestamp = customFormatter.FullTimestamp
logger.AddHook(&fileLogHook{
Writer: file,
Formatter: fileFormatter,
})
} else {
// logging to file only
// turn off the colouring for the file
customFormatter.ForceColors = false
logger.Out = file
}
}
// otherwise, output to StdErr

View File

@ -4,6 +4,7 @@
* Added interface options to disable creating performers/studios/tags from dropdown selectors. ([#1814](https://github.com/stashapp/stash/pull/1814))
### 🐛 Bug fixes
* Fix colour codes not outputting correctly when logging to file on Windows. ([#1846](https://github.com/stashapp/stash/pull/1846))
* Sort directory listings using case sensitive collation. ([#1823](https://github.com/stashapp/stash/pull/1823))
* Fix auto-tag logic for names which have single-letter words. ([#1817](https://github.com/stashapp/stash/pull/1817))
* Fix huge memory usage spike during clean task. ([#1805](https://github.com/stashapp/stash/pull/1805))