forked from ochinchina/supervisord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logtail.go
73 lines (65 loc) · 1.9 KB
/
logtail.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"github.com/gorilla/mux"
logger "github.com/ochinchina/supervisord/logger"
"net/http"
)
// Logtail tail the process log through http interface
type Logtail struct {
router *mux.Router
supervisor *Supervisor
}
// NewLogtail create a Logtail object
func NewLogtail(supervisor *Supervisor) *Logtail {
return &Logtail{router: mux.NewRouter(), supervisor: supervisor}
}
// CreateHandler create http handlers to process the program stdout and stderr through http interface
func (lt *Logtail) CreateHandler() http.Handler {
lt.router.HandleFunc("/logtail/{program}/stdout", lt.getStdoutLog).Methods("GET")
lt.router.HandleFunc("/logtail/{program}/stderr", lt.getStderrLog).Methods("GET")
return lt.router
}
func (lt *Logtail) getStdoutLog(w http.ResponseWriter, req *http.Request) {
lt.getLog("stdout", w, req)
}
func (lt *Logtail) getStderrLog(w http.ResponseWriter, req *http.Request) {
lt.getLog("stderr", w, req)
}
func (lt *Logtail) getLog(logType string, w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
program := vars["program"]
procMgr := lt.supervisor.GetManager()
proc := procMgr.Find(program)
if proc == nil {
w.WriteHeader(http.StatusBadRequest)
} else {
var ok bool = false
var compositeLogger *logger.CompositeLogger = nil
if logType == "stdout" {
compositeLogger, ok = proc.StdoutLog.(*logger.CompositeLogger)
} else {
compositeLogger, ok = proc.StderrLog.(*logger.CompositeLogger)
}
if ok {
w.Header().Set("Transfer-Encoding", "chunked")
w.WriteHeader(http.StatusOK)
flusher, _ := w.(http.Flusher)
ch := make(chan []byte, 100)
chanLogger := logger.NewChanLogger(ch)
compositeLogger.AddLogger(chanLogger)
for {
text, ok := <-ch
if !ok {
break
}
_, err := w.Write(text)
if err != nil {
break
}
flusher.Flush()
}
compositeLogger.RemoveLogger(chanLogger)
chanLogger.Close()
}
}
}