/
service-logs.go
51 lines (44 loc) · 1.21 KB
/
service-logs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package handlers
import (
"fmt"
"io"
"net/http"
"github.com/docker/docker/api/types"
docker "github.com/docker/docker/client"
"github.com/docker/docker/pkg/ioutils"
"github.com/gorilla/mux"
)
// GetProjectServiceLogs retrieves service logs for a project
func GetProjectServiceLogs(w http.ResponseWriter, r *http.Request) {
if _, ok := w.(http.Flusher); !ok {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "streams not supported")
return
}
// traefik listens for this content type to push streams.
w.Header().Set("Content-Type", "text/event-stream")
c, err := docker.NewEnvClient()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "could not get docker client: %v\n", err)
return
}
p := mux.Vars(r)["project"]
env := r.URL.Query().Get("env")
s := mux.Vars(r)["service"]
sID := fmt.Sprintf("%v_%v_%v", p, env, s)
rc, err := c.ServiceLogs(r.Context(), sID, types.ContainerLogsOptions{
ShowStderr: true,
ShowStdout: true,
Follow: true,
Tail: "20",
})
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "could not get logs from docker: %v\n", err)
return
}
wf := ioutils.NewWriteFlusher(w)
defer wf.Close()
io.Copy(wf, rc)
}