feat: structured logging improvements

This change adds a child logger with request information to the
http request context. Also improved the log format for clarity.

- Unescaped the query string
- Use JSON log format when not in dev mode.
- Added request ip to the request child logger.
- The child logger is passed to the converter so we can associate
  any errors with a specific request / file.
- Add book file name as a logger attribute
- Add user agent header as a logger attribute
- Log the "X-Forwarded-For" header, falling back to RemoteAddr
This commit is contained in:
Evan Buss
2024-08-10 20:03:34 +00:00
parent be78d83bd6
commit ccc6217014
8 changed files with 68 additions and 15 deletions

View File

@@ -1,9 +1,11 @@
package convert
import "log/slog"
type Converter interface {
// Whether or not the converter is available
// Usually based on the availability of the underlying tool
Available() bool
// Convert the input file to the output file
Convert(input string) (string, error)
Convert(log *slog.Logger, input string) (string, error)
}

View File

@@ -1,6 +1,7 @@
package convert
import (
"log/slog"
"os/exec"
"strings"
"sync"
@@ -21,7 +22,7 @@ func (kc *KepubConverter) Available() bool {
return kc.available
}
func (kc *KepubConverter) Convert(input string) (string, error) {
func (kc *KepubConverter) Convert(_ *slog.Logger, input string) (string, error) {
kc.mutex.Lock()
defer kc.mutex.Unlock()

View File

@@ -23,7 +23,7 @@ func (mc *MobiConverter) Available() bool {
return mc.available
}
func (mc *MobiConverter) Convert(input string) (string, error) {
func (mc *MobiConverter) Convert(log *slog.Logger, input string) (string, error) {
mc.mutex.Lock()
defer mc.mutex.Unlock()
@@ -49,14 +49,14 @@ func (mc *MobiConverter) Convert(input string) (string, error) {
isError := true
if exiterr, ok := err.(*exec.ExitError); ok {
// Sometimes warnings cause a 1 exit-code, but the file is still created
slog.Info("Exit code", slog.Any("code", exiterr.ExitCode()))
log.Info("Exit code", slog.Any("code", exiterr.ExitCode()))
if exiterr.ExitCode() == 1 {
isError = false
}
}
if isError {
slog.Error("Error converting file",
log.Error("Error converting file",
slog.Any("error", err),
slog.String("stdout", out.String()),
slog.String("stderr", stderr.String()),