feat: allow logging to stdout

The --log option accepts "-" as filename. This prevents rest-server from
opening the log file, it simply writes to the STDOUT stream provided by
the caller.

**BREAKING** in case use really used "-" to specify a file named "-"
you'll need to update your rest-server invocation to use "./-".
This commit is contained in:
Heiko Schlittermann (HS12-RIPE) 2023-03-23 19:19:18 +01:00
parent 94d5861c50
commit 9f074d8b3a
No known key found for this signature in database
GPG key ID: AF4CC676A6B6C142
3 changed files with 25 additions and 4 deletions

View file

@ -0,0 +1,13 @@
Feature: Allows "-" as filename for the `--log` option.
When (e.g. for debugging purpose) the rest server is invoked like
sudo -u restic rest-server … --log /dev/stdout
it tries to open `/dev/stdout` (O_CREATE, O_WRITE, O_APPEND). This
operation fails, as in the above invocation, `/dev/stdout` is owned by
the caller (here: root) and only writable for the caller. Subprocesses
get just the filedescriptor. Using `/proc/self/fd/1` didn't work either,
for the same reasons.
https://github.com/restic/rest-server/pull/217

View file

@ -46,7 +46,7 @@ func init() {
flags.StringVar(&cpuProfile, "cpu-profile", cpuProfile, "write CPU profile to file")
flags.BoolVar(&server.Debug, "debug", server.Debug, "output debug messages")
flags.StringVar(&server.Listen, "listen", server.Listen, "listen address")
flags.StringVar(&server.Log, "log", server.Log, "write HTTP requests in the combined log format to the specified `filename`")
flags.StringVar(&server.Log, "log", server.Log, "write HTTP requests in the combined log format to the specified `filename` (use \"-\" for logging to stdout)")
flags.Int64Var(&server.MaxRepoSize, "max-size", server.MaxRepoSize, "the maximum size of the repository in bytes")
flags.StringVar(&server.Path, "path", server.Path, "data directory")
flags.BoolVar(&server.TLS, "tls", server.TLS, "turn on TLS support")

14
mux.go
View file

@ -2,6 +2,7 @@ package restserver
import (
"fmt"
"io"
"log"
"net/http"
"os"
@ -21,9 +22,16 @@ func (s *Server) debugHandler(next http.Handler) http.Handler {
}
func (s *Server) logHandler(next http.Handler) http.Handler {
accessLog, err := os.OpenFile(s.Log, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
log.Fatalf("error: %v", err)
var accessLog io.Writer
if s.Log == "-" {
accessLog = os.Stdout
} else {
var err error
accessLog, err = os.OpenFile(s.Log, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
log.Fatalf("error: %v", err)
}
}
return handlers.CombinedLoggingHandler(accessLog, next)