new logging

This commit is contained in:
Liang Ding 2014-12-13 18:47:41 +08:00
parent 27f0897faa
commit cb14485388
19 changed files with 304 additions and 215 deletions

View File

@ -29,8 +29,8 @@ import (
"time" "time"
"github.com/b3log/wide/event" "github.com/b3log/wide/event"
"github.com/b3log/wide/log"
"github.com/b3log/wide/util" "github.com/b3log/wide/util"
"github.com/golang/glog"
) )
const ( const (
@ -93,6 +93,7 @@ type conf struct {
Context string // server context Context string // server context
Server string // server host and port ({IP}:{Port}) Server string // server host and port ({IP}:{Port})
StaticServer string // static resources server scheme, host and port (http://{IP}:{Port}) StaticServer string // static resources server scheme, host and port (http://{IP}:{Port})
LogLevel string // logging level
Channel string // channel (ws://{IP}:{Port}) Channel string // channel (ws://{IP}:{Port})
HTTPSessionMaxAge int // HTTP session max age (in seciond) HTTPSessionMaxAge int // HTTP session max age (in seciond)
StaticResourceVersion string // version of static resources StaticResourceVersion string // version of static resources
@ -111,6 +112,9 @@ var Wide conf
// Save function will use this variable to persist. // Save function will use this variable to persist.
var rawWide conf var rawWide conf
// Logger.
var logger = log.NewLogger(os.Stdout)
// FixedTimeCheckEnv checks Wide runtime enviorment periodically (7 minutes). // FixedTimeCheckEnv checks Wide runtime enviorment periodically (7 minutes).
// //
// Exits process if found fatal issues (such as not found $GOPATH), // Exits process if found fatal issues (such as not found $GOPATH),
@ -129,14 +133,14 @@ func checkEnv() {
cmd := exec.Command("go", "version") cmd := exec.Command("go", "version")
buf, err := cmd.CombinedOutput() buf, err := cmd.CombinedOutput()
if nil != err { if nil != err {
glog.Fatal("Not found 'go' command, please make sure Go has been installed correctly") logger.Error("Not found 'go' command, please make sure Go has been installed correctly")
os.Exit(-1) os.Exit(-1)
} }
glog.V(5).Info(string(buf)) logger.Debug(string(buf))
if "" == os.Getenv("GOPATH") { if "" == os.Getenv("GOPATH") {
glog.Fatal("Not found $GOPATH, please configure it before running Wide") logger.Error("Not found $GOPATH, please configure it before running Wide")
os.Exit(-1) os.Exit(-1)
} }
@ -147,7 +151,7 @@ func checkEnv() {
if nil != err { if nil != err {
event.EventQueue <- &event.Event{Code: event.EvtCodeGocodeNotFound} event.EventQueue <- &event.Event{Code: event.EvtCodeGocodeNotFound}
glog.Warningf("Not found gocode [%s]", gocode) logger.Warnf("Not found gocode [%s]", gocode)
} }
ideStub := util.Go.GetExecutableInGOBIN("ide_stub") ideStub := util.Go.GetExecutableInGOBIN("ide_stub")
@ -156,7 +160,7 @@ func checkEnv() {
if nil != err { if nil != err {
event.EventQueue <- &event.Event{Code: event.EvtCodeIDEStubNotFound} event.EventQueue <- &event.Event{Code: event.EvtCodeIDEStubNotFound}
glog.Warningf("Not found ide_stub [%s]", ideStub) logger.Warnf("Not found ide_stub [%s]", ideStub)
} }
} }
@ -192,7 +196,7 @@ func (c *conf) GetGoFmt(username string) string {
case "goimports": case "goimports":
return util.Go.GetExecutableInGOBIN("goimports") return util.Go.GetExecutableInGOBIN("goimports")
default: default:
glog.Errorf("Unsupported Go Format tool [%s]", user.GoFormat) logger.Errorf("Unsupported Go Format tool [%s]", user.GoFormat)
return "gofmt" return "gofmt"
} }
} }
@ -234,13 +238,13 @@ func Save() bool {
bytes, err := json.MarshalIndent(rawWide, "", " ") bytes, err := json.MarshalIndent(rawWide, "", " ")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
return false return false
} }
if err = ioutil.WriteFile("conf/wide.json", bytes, 0644); nil != err { if err = ioutil.WriteFile("conf/wide.json", bytes, 0644); nil != err {
glog.Error(err) logger.Error(err)
return false return false
} }
@ -254,29 +258,31 @@ func Load(confPath, confIP, confPort, confServer, confStaticServer, confContext,
err := json.Unmarshal(bytes, &Wide) err := json.Unmarshal(bytes, &Wide)
if err != nil { if err != nil {
glog.Error("Parses wide.json error: ", err) logger.Error("Parses wide.json error: ", err)
os.Exit(-1) os.Exit(-1)
} }
log.SetLevel(Wide.LogLevel)
// keep the raw content // keep the raw content
json.Unmarshal(bytes, &rawWide) json.Unmarshal(bytes, &rawWide)
glog.V(5).Info("Conf: \n" + string(bytes)) logger.Debug("Conf: \n" + string(bytes))
// Working Driectory // Working Driectory
Wide.WD = util.OS.Pwd() Wide.WD = util.OS.Pwd()
glog.V(5).Infof("${pwd} [%s]", Wide.WD) logger.Debugf("${pwd} [%s]", Wide.WD)
// IP // IP
ip, err := util.Net.LocalIP() ip, err := util.Net.LocalIP()
if err != nil { if err != nil {
glog.Error(err) logger.Error(err)
os.Exit(-1) os.Exit(-1)
} }
glog.V(5).Infof("${ip} [%s]", ip) logger.Debugf("${ip} [%s]", ip)
if confDocker { if confDocker {
// TODO: may be we need to do something here // TODO: may be we need to do something here
@ -374,7 +380,7 @@ func UpdateCustomizedConf(username string) {
t, err := template.ParseFiles("static/user/style.css.tmpl") t, err := template.ParseFiles("static/user/style.css.tmpl")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
os.Exit(-1) os.Exit(-1)
} }
@ -382,14 +388,14 @@ func UpdateCustomizedConf(username string) {
wd := util.OS.Pwd() wd := util.OS.Pwd()
dir := filepath.Clean(wd + "/static/user/" + u.Name) dir := filepath.Clean(wd + "/static/user/" + u.Name)
if err := os.MkdirAll(dir, 0755); nil != err { if err := os.MkdirAll(dir, 0755); nil != err {
glog.Error(err) logger.Error(err)
os.Exit(-1) os.Exit(-1)
} }
fout, err := os.Create(dir + PathSeparator + "style.css") fout, err := os.Create(dir + PathSeparator + "style.css")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
os.Exit(-1) os.Exit(-1)
} }
@ -397,7 +403,7 @@ func UpdateCustomizedConf(username string) {
defer fout.Close() defer fout.Close()
if err := t.Execute(fout, model); nil != err { if err := t.Execute(fout, model); nil != err {
glog.Error(err) logger.Error(err)
os.Exit(-1) os.Exit(-1)
} }
@ -435,12 +441,10 @@ func CreateWorkspaceDir(path string) {
func createDir(path string) { func createDir(path string) {
if !util.File.IsExist(path) { if !util.File.IsExist(path) {
if err := os.MkdirAll(path, 0775); nil != err { if err := os.MkdirAll(path, 0775); nil != err {
glog.Error(err) logger.Error(err)
os.Exit(-1) os.Exit(-1)
} }
glog.V(7).Infof("Created a directory [%s]", path)
} }
} }

View File

@ -4,6 +4,7 @@
"Context": "", "Context": "",
"Server": "{IP}:{Port}", "Server": "{IP}:{Port}",
"StaticServer": "", "StaticServer": "",
"LogLevel": "info",
"Channel": "ws://{IP}:{Port}", "Channel": "ws://{IP}:{Port}",
"HTTPSessionMaxAge": 86400, "HTTPSessionMaxAge": 86400,
"StaticResourceVersion": "${time}", "StaticResourceVersion": "${time}",

View File

@ -29,12 +29,15 @@ import (
"github.com/b3log/wide/conf" "github.com/b3log/wide/conf"
"github.com/b3log/wide/file" "github.com/b3log/wide/file"
"github.com/b3log/wide/log"
"github.com/b3log/wide/session" "github.com/b3log/wide/session"
"github.com/b3log/wide/util" "github.com/b3log/wide/util"
"github.com/golang/glog"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
) )
// Logger.
var logger = log.NewLogger(os.Stdout)
// WSHandler handles request of creating editor channel. // WSHandler handles request of creating editor channel.
// XXX: NOT used at present // XXX: NOT used at present
func WSHandler(w http.ResponseWriter, r *http.Request) { func WSHandler(w http.ResponseWriter, r *http.Request) {
@ -58,7 +61,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) {
session.EditorWS[sid] = &editorChan session.EditorWS[sid] = &editorChan
glog.Infof("Open a new [Editor] with session [%s], %d", sid, len(session.EditorWS)) logger.Infof("Open a new [Editor] with session [%s], %d", sid, len(session.EditorWS))
args := map[string]interface{}{} args := map[string]interface{}{}
for { for {
@ -72,7 +75,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) {
offset := getCursorOffset(code, line, ch) offset := getCursorOffset(code, line, ch)
// glog.Infof("offset: %d", offset) // logger.Infof("offset: %d", offset)
gocode := util.Go.GetExecutableInGOBIN("gocode") gocode := util.Go.GetExecutableInGOBIN("gocode")
argv := []string{"-f=json", "autocomplete", strconv.Itoa(offset)} argv := []string{"-f=json", "autocomplete", strconv.Itoa(offset)}
@ -91,7 +94,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) {
ret = map[string]interface{}{"output": string(output.Bytes()), "cmd": "autocomplete"} ret = map[string]interface{}{"output": string(output.Bytes()), "cmd": "autocomplete"}
if err := session.EditorWS[sid].WriteJSON(&ret); err != nil { if err := session.EditorWS[sid].WriteJSON(&ret); err != nil {
glog.Error("Editor WS ERROR: " + err.Error()) logger.Error("Editor WS ERROR: " + err.Error())
return return
} }
} }
@ -102,7 +105,7 @@ func AutocompleteHandler(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -121,7 +124,7 @@ func AutocompleteHandler(w http.ResponseWriter, r *http.Request) {
fout, err := os.Create(path) fout, err := os.Create(path)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -131,7 +134,7 @@ func AutocompleteHandler(w http.ResponseWriter, r *http.Request) {
fout.WriteString(code) fout.WriteString(code)
if err := fout.Close(); nil != err { if err := fout.Close(); nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -142,7 +145,7 @@ func AutocompleteHandler(w http.ResponseWriter, r *http.Request) {
offset := getCursorOffset(code, line, ch) offset := getCursorOffset(code, line, ch)
// glog.Infof("offset: %d", offset) // logger.Infof("offset: %d", offset)
userWorkspace := conf.Wide.GetUserWorkspace(username) userWorkspace := conf.Wide.GetUserWorkspace(username)
workspaces := filepath.SplitList(userWorkspace) workspaces := filepath.SplitList(userWorkspace)
@ -153,7 +156,7 @@ func AutocompleteHandler(w http.ResponseWriter, r *http.Request) {
libPath += userLib + conf.PathListSeparator libPath += userLib + conf.PathListSeparator
} }
glog.V(5).Infof("gocode set lib-path %s", libPath) logger.Debugf("gocode set lib-path [%s]", libPath)
// FIXME: using gocode set lib-path has some issues while accrossing workspaces // FIXME: using gocode set lib-path has some issues while accrossing workspaces
gocode := util.Go.GetExecutableInGOBIN("gocode") gocode := util.Go.GetExecutableInGOBIN("gocode")
@ -169,7 +172,7 @@ func AutocompleteHandler(w http.ResponseWriter, r *http.Request) {
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -189,7 +192,7 @@ func GetExprInfoHandler(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -202,7 +205,7 @@ func GetExprInfoHandler(w http.ResponseWriter, r *http.Request) {
fout, err := os.Create(path) fout, err := os.Create(path)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -212,7 +215,7 @@ func GetExprInfoHandler(w http.ResponseWriter, r *http.Request) {
fout.WriteString(code) fout.WriteString(code)
if err := fout.Close(); nil != err { if err := fout.Close(); nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -223,7 +226,7 @@ func GetExprInfoHandler(w http.ResponseWriter, r *http.Request) {
offset := getCursorOffset(code, line, ch) offset := getCursorOffset(code, line, ch)
// glog.Infof("offset [%d]", offset) // logger.Infof("offset [%d]", offset)
ideStub := util.Go.GetExecutableInGOBIN("ide_stub") ideStub := util.Go.GetExecutableInGOBIN("ide_stub")
argv := []string{"type", "-cursor", filename + ":" + strconv.Itoa(offset), "-info", "."} argv := []string{"type", "-cursor", filename + ":" + strconv.Itoa(offset), "-info", "."}
@ -234,7 +237,7 @@ func GetExprInfoHandler(w http.ResponseWriter, r *http.Request) {
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -265,7 +268,7 @@ func FindDeclarationHandler(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -278,7 +281,7 @@ func FindDeclarationHandler(w http.ResponseWriter, r *http.Request) {
fout, err := os.Create(path) fout, err := os.Create(path)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -288,7 +291,7 @@ func FindDeclarationHandler(w http.ResponseWriter, r *http.Request) {
fout.WriteString(code) fout.WriteString(code)
if err := fout.Close(); nil != err { if err := fout.Close(); nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -299,7 +302,7 @@ func FindDeclarationHandler(w http.ResponseWriter, r *http.Request) {
offset := getCursorOffset(code, line, ch) offset := getCursorOffset(code, line, ch)
// glog.Infof("offset [%d]", offset) // logger.Infof("offset [%d]", offset)
ideStub := util.Go.GetExecutableInGOBIN("ide_stub") ideStub := util.Go.GetExecutableInGOBIN("ide_stub")
argv := []string{"type", "-cursor", filename + ":" + strconv.Itoa(offset), "-def", "."} argv := []string{"type", "-cursor", filename + ":" + strconv.Itoa(offset), "-def", "."}
@ -310,7 +313,7 @@ func FindDeclarationHandler(w http.ResponseWriter, r *http.Request) {
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -350,7 +353,7 @@ func FindUsagesHandler(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -363,7 +366,7 @@ func FindUsagesHandler(w http.ResponseWriter, r *http.Request) {
fout, err := os.Create(filePath) fout, err := os.Create(filePath)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -373,7 +376,7 @@ func FindUsagesHandler(w http.ResponseWriter, r *http.Request) {
fout.WriteString(code) fout.WriteString(code)
if err := fout.Close(); nil != err { if err := fout.Close(); nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -383,7 +386,7 @@ func FindUsagesHandler(w http.ResponseWriter, r *http.Request) {
ch := int(args["cursorCh"].(float64)) ch := int(args["cursorCh"].(float64))
offset := getCursorOffset(code, line, ch) offset := getCursorOffset(code, line, ch)
// glog.Infof("offset [%d]", offset) // logger.Infof("offset [%d]", offset)
ideStub := util.Go.GetExecutableInGOBIN("ide_stub") ideStub := util.Go.GetExecutableInGOBIN("ide_stub")
argv := []string{"type", "-cursor", filename + ":" + strconv.Itoa(offset), "-use", "."} argv := []string{"type", "-cursor", filename + ":" + strconv.Itoa(offset), "-use", "."}
@ -394,7 +397,7 @@ func FindUsagesHandler(w http.ResponseWriter, r *http.Request) {
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return

View File

@ -23,7 +23,6 @@ import (
"github.com/b3log/wide/conf" "github.com/b3log/wide/conf"
"github.com/b3log/wide/session" "github.com/b3log/wide/session"
"github.com/b3log/wide/util" "github.com/b3log/wide/util"
"github.com/golang/glog"
) )
// GoFmtHandler handles request of formatting Go source code. // GoFmtHandler handles request of formatting Go source code.
@ -46,7 +45,7 @@ func GoFmtHandler(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -62,7 +61,7 @@ func GoFmtHandler(w http.ResponseWriter, r *http.Request) {
fout, err := os.Create(filePath) fout, err := os.Create(filePath)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -72,7 +71,7 @@ func GoFmtHandler(w http.ResponseWriter, r *http.Request) {
fout.WriteString(code) fout.WriteString(code)
if err := fout.Close(); nil != err { if err := fout.Close(); nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -99,7 +98,7 @@ func GoFmtHandler(w http.ResponseWriter, r *http.Request) {
fout, err = os.Create(filePath) fout, err = os.Create(filePath)
fout.WriteString(code) fout.WriteString(code)
if err := fout.Close(); nil != err { if err := fout.Close(); nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return

View File

@ -15,7 +15,11 @@
// Package event includes event related manipulations. // Package event includes event related manipulations.
package event package event
import "github.com/golang/glog" import (
"os"
"github.com/b3log/wide/log"
)
const ( const (
// EvtCodeGOPATHNotFound indicates an event: not found $GOPATH env variable // EvtCodeGOPATHNotFound indicates an event: not found $GOPATH env variable
@ -33,6 +37,9 @@ const (
// Max length of queue. // Max length of queue.
const maxQueueLength = 10 const maxQueueLength = 10
// Logger.
var logger = log.NewLogger(os.Stdout)
// Event represents an event. // Event represents an event.
type Event struct { type Event struct {
Code int `json:"code"` // event code Code int `json:"code"` // event code
@ -63,7 +70,7 @@ var UserEventQueues = queues{}
func Load() { func Load() {
go func() { go func() {
for event := range EventQueue { for event := range EventQueue {
glog.V(5).Infof("Received a global event [code=%d]", event.Code) logger.Debugf("Received a global event [code=%d]", event.Code)
// dispatch the event to each user event queue // dispatch the event to each user event queue
for _, userQueue := range UserEventQueues { for _, userQueue := range UserEventQueues {
@ -86,7 +93,7 @@ func (uq *UserEventQueue) AddHandler(handlers ...Handler) {
func (ueqs queues) New(sid string) *UserEventQueue { func (ueqs queues) New(sid string) *UserEventQueue {
q := ueqs[sid] q := ueqs[sid]
if nil != q { if nil != q {
glog.Warningf("Already exist a user queue in session [%s]", sid) logger.Warnf("Already exist a user queue in session [%s]", sid)
return q return q
} }
@ -100,7 +107,7 @@ func (ueqs queues) New(sid string) *UserEventQueue {
go func() { // start listening go func() { // start listening
for evt := range q.Queue { for evt := range q.Queue {
glog.V(5).Infof("Session [%s] received an event [%d]", sid, evt.Code) logger.Debugf("Session [%s] received an event [%d]", sid, evt.Code)
// process event by each handlers // process event by each handlers
for _, handler := range q.Handlers { for _, handler := range q.Handlers {

View File

@ -21,7 +21,6 @@ import (
"path/filepath" "path/filepath"
"github.com/b3log/wide/util" "github.com/b3log/wide/util"
"github.com/golang/glog"
) )
// GetZip handles request of retrieving zip file. // GetZip handles request of retrieving zip file.
@ -57,7 +56,7 @@ func CreateZip(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -75,7 +74,7 @@ func CreateZip(w http.ResponseWriter, r *http.Request) {
zipFile, err := util.Zip.Create(path + ".zip") zipFile, err := util.Zip.Create(path + ".zip")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return

View File

@ -26,11 +26,14 @@ import (
"github.com/b3log/wide/conf" "github.com/b3log/wide/conf"
"github.com/b3log/wide/event" "github.com/b3log/wide/event"
"github.com/b3log/wide/log"
"github.com/b3log/wide/session" "github.com/b3log/wide/session"
"github.com/b3log/wide/util" "github.com/b3log/wide/util"
"github.com/golang/glog"
) )
// Logger.
var logger = log.NewLogger(os.Stdout)
// Node represents a file node in file tree. // Node represents a file node in file tree.
type Node struct { type Node struct {
Name string `json:"name"` Name string `json:"name"`
@ -120,7 +123,7 @@ func RefreshDirectory(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
data, err := json.Marshal(node.Children) data, err := json.Marshal(node.Children)
if err != nil { if err != nil {
glog.Error(err) logger.Error(err)
return return
} }
@ -135,7 +138,7 @@ func GetFile(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -162,7 +165,7 @@ func GetFile(w http.ResponseWriter, r *http.Request) {
user := GetUsre(path) user := GetUsre(path)
if nil == user { if nil == user {
glog.Warningf("The path [%s] has no owner") logger.Warnf("The path [%s] has no owner")
data["path"] = "" data["path"] = ""
return return
@ -193,7 +196,7 @@ func SaveFile(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -205,7 +208,7 @@ func SaveFile(w http.ResponseWriter, r *http.Request) {
fout, err := os.Create(filePath) fout, err := os.Create(filePath)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -216,7 +219,7 @@ func SaveFile(w http.ResponseWriter, r *http.Request) {
fout.WriteString(code) fout.WriteString(code)
if err := fout.Close(); nil != err { if err := fout.Close(); nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
wSession := session.WideSessions.Get(sid) wSession := session.WideSessions.Get(sid)
@ -235,7 +238,7 @@ func NewFile(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -270,7 +273,7 @@ func RemoveFile(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -297,7 +300,7 @@ func RenameFile(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -336,7 +339,7 @@ func Find(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -385,7 +388,7 @@ func SearchText(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -429,7 +432,7 @@ func walk(path string, node *Node, creatable, removable bool) {
node.Children = append(node.Children, &child) node.Children = append(node.Children, &child)
if nil == fio { if nil == fio {
glog.Warningf("Path [%s] is nil", fpath) logger.Warnf("Path [%s] is nil", fpath)
continue continue
} }
@ -471,7 +474,7 @@ func listFiles(dirname string) []string {
fio, err := os.Lstat(path) fio, err := os.Lstat(path)
if nil != err { if nil != err {
glog.Warningf("Can't read file info [%s]", path) logger.Warnf("Can't read file info [%s]", path)
continue continue
} }
@ -562,30 +565,30 @@ func createFile(path, fileType string) bool {
case "f": case "f":
file, err := os.OpenFile(path, os.O_CREATE, 0775) file, err := os.OpenFile(path, os.O_CREATE, 0775)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
return false return false
} }
defer file.Close() defer file.Close()
glog.V(5).Infof("Created file [%s]", path) logger.Debugf("Created file [%s]", path)
return true return true
case "d": case "d":
err := os.Mkdir(path, 0775) err := os.Mkdir(path, 0775)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
return false return false
} }
glog.V(5).Infof("Created directory [%s]", path) logger.Debugf("Created directory [%s]", path)
return true return true
default: default:
glog.Errorf("Unsupported file type [%s]", fileType) logger.Errorf("Unsupported file type [%s]", fileType)
return false return false
} }
@ -594,12 +597,12 @@ func createFile(path, fileType string) bool {
// removeFile removes file on the specified path. // removeFile removes file on the specified path.
func removeFile(path string) bool { func removeFile(path string) bool {
if err := os.RemoveAll(path); nil != err { if err := os.RemoveAll(path); nil != err {
glog.Errorf("Removes [%s] failed: [%s]", path, err.Error()) logger.Errorf("Removes [%s] failed: [%s]", path, err.Error())
return false return false
} }
glog.V(5).Infof("Removed [%s]", path) logger.Debugf("Removed [%s]", path)
return true return true
} }
@ -607,12 +610,12 @@ func removeFile(path string) bool {
// renameFile renames (moves) a file from the specified old path to the specified new path. // renameFile renames (moves) a file from the specified old path to the specified new path.
func renameFile(oldPath, newPath string) bool { func renameFile(oldPath, newPath string) bool {
if err := os.Rename(oldPath, newPath); nil != err { if err := os.Rename(oldPath, newPath); nil != err {
glog.Errorf("Renames [%s] failed: [%s]", oldPath, err.Error()) logger.Errorf("Renames [%s] failed: [%s]", oldPath, err.Error())
return false return false
} }
glog.V(5).Infof("Renamed [%s] to [%s]", oldPath, newPath) logger.Debugf("Renamed [%s] to [%s]", oldPath, newPath)
return true return true
} }
@ -632,7 +635,7 @@ func find(dir, name string, results []*string) []*string {
f.Close() f.Close()
if nil != err { if nil != err {
glog.Errorf("Read dir [%s] failed: [%s]", dir, err.Error()) logger.Errorf("Read dir [%s] failed: [%s]", dir, err.Error())
return results return results
} }
@ -655,7 +658,7 @@ func find(dir, name string, results []*string) []*string {
match, err := filepath.Match(strings.ToLower(pattern), strings.ToLower(path)) match, err := filepath.Match(strings.ToLower(pattern), strings.ToLower(path))
if nil != err { if nil != err {
glog.Errorf("Find match filename failed: [%s]", err.Error) logger.Errorf("Find match filename failed: [%s]", err.Error)
continue continue
} }
@ -681,7 +684,7 @@ func search(dir, extension, text string, snippets []*Snippet) []*Snippet {
f.Close() f.Close()
if nil != err { if nil != err {
glog.Errorf("Read dir [%s] failed: [%s]", dir, err.Error()) logger.Errorf("Read dir [%s] failed: [%s]", dir, err.Error())
return snippets return snippets
} }
@ -709,7 +712,7 @@ func searchInFile(path string, text string) []*Snippet {
bytes, err := ioutil.ReadFile(path) bytes, err := ioutil.ReadFile(path)
if nil != err { if nil != err {
glog.Errorf("Read file [%s] failed: [%s]", path, err.Error()) logger.Errorf("Read file [%s] failed: [%s]", path, err.Error())
return ret return ret
} }

View File

@ -22,9 +22,12 @@ import (
"sort" "sort"
"strings" "strings"
"github.com/golang/glog" "github.com/b3log/wide/log"
) )
// Logger.
var logger = log.NewLogger(os.Stdout)
// Locale. // Locale.
type locale struct { type locale struct {
Name string Name string
@ -54,7 +57,7 @@ func Load() {
func load(localeStr string) { func load(localeStr string) {
bytes, err := ioutil.ReadFile("i18n/" + localeStr + ".json") bytes, err := ioutil.ReadFile("i18n/" + localeStr + ".json")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
os.Exit(-1) os.Exit(-1)
} }
@ -63,14 +66,14 @@ func load(localeStr string) {
err = json.Unmarshal(bytes, &l.Langs) err = json.Unmarshal(bytes, &l.Langs)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
os.Exit(-1) os.Exit(-1)
} }
Locales[localeStr] = l Locales[localeStr] = l
glog.V(5).Infof("Loaded [%s] locale configuration", localeStr) logger.Debugf("Loaded [%s] locale configuration", localeStr)
} }
// Get gets message with the specified locale and key. // Get gets message with the specified locale and key.

View File

@ -14,7 +14,8 @@
// Package log includes logging related manipulations. // Package log includes logging related manipulations.
// //
// logger := log.NewLogger(os.Stdout, log.Debug) // log.Level = log.Debug
// logger := log.NewLogger(os.Stdout)
// //
// logger.Debug("debug message") // logger.Debug("debug message")
// logger.Info("info message") // logger.Info("info message")
@ -28,6 +29,7 @@ import (
"fmt" "fmt"
"io" "io"
stdlog "log" stdlog "log"
"strings"
) )
// Logging level. // Logging level.
@ -38,20 +40,65 @@ const (
Error Error
) )
// Logger is a simple logger with level. // all loggers.
// The underlying logger is the Go standard logging "log". var loggers []*Logger
// the global default logging level, it will be used for creating logger.
var logLevel = Debug
// Logger represents a simple logger with level.
// The underlying logger is the standard Go logging "log".
type Logger struct { type Logger struct {
level int level int
logger *stdlog.Logger logger *stdlog.Logger
} }
// NewLogger creates a logger. // NewLogger creates a logger.
func NewLogger(out io.Writer, level int) *Logger { func NewLogger(out io.Writer) *Logger {
ret := &Logger{level: level, logger: stdlog.New(out, "", stdlog.Ldate|stdlog.Ltime|stdlog.Lshortfile)} ret := &Logger{level: logLevel, logger: stdlog.New(out, "", stdlog.Ldate|stdlog.Ltime|stdlog.Lshortfile)}
loggers = append(loggers, ret)
return ret return ret
} }
// SetLevel sets the logging level of all loggers.
func SetLevel(level string) {
logLevel = getLevel(level)
for _, l := range loggers {
l.SetLevel(level)
}
}
// getLevel gets logging level int value corresponding to the specified level.
func getLevel(level string) int {
level = strings.ToLower(level)
switch level {
case "debug":
return Debug
case "info":
return Info
case "warn":
return Warn
case "error":
return Error
default:
return Info
}
}
// SetLevel sets the logging level of a logger.
func (l *Logger) SetLevel(level string) {
l.level = getLevel(level)
}
// IsDebugEnabled determines whether the debug level is enabled.
func (l *Logger) IsDebugEnabled() bool {
return l.level <= Debug
}
// Debug prints debug level message. // Debug prints debug level message.
func (l *Logger) Debug(v ...interface{}) { func (l *Logger) Debug(v ...interface{}) {
if Debug < l.level { if Debug < l.level {

37
main.go
View File

@ -33,14 +33,17 @@ import (
"github.com/b3log/wide/event" "github.com/b3log/wide/event"
"github.com/b3log/wide/file" "github.com/b3log/wide/file"
"github.com/b3log/wide/i18n" "github.com/b3log/wide/i18n"
"github.com/b3log/wide/log"
"github.com/b3log/wide/notification" "github.com/b3log/wide/notification"
"github.com/b3log/wide/output" "github.com/b3log/wide/output"
"github.com/b3log/wide/session" "github.com/b3log/wide/session"
"github.com/b3log/wide/shell" "github.com/b3log/wide/shell"
"github.com/b3log/wide/util" "github.com/b3log/wide/util"
"github.com/golang/glog"
) )
// Logger
var logger *log.Logger
// The only one init function in Wide. // The only one init function in Wide.
func init() { func init() {
confPath := flag.String("conf", "conf/wide.json", "path of wide.json") confPath := flag.String("conf", "conf/wide.json", "path of wide.json")
@ -52,16 +55,16 @@ func init() {
confChannel := flag.String("channel", "", "this will overwrite Wide.XXXChannel if specified") confChannel := flag.String("channel", "", "this will overwrite Wide.XXXChannel if specified")
confStat := flag.Bool("stat", false, "whether report statistics periodically") confStat := flag.Bool("stat", false, "whether report statistics periodically")
confDocker := flag.Bool("docker", false, "whether run in a docker container") confDocker := flag.Bool("docker", false, "whether run in a docker container")
// confLogLevel := flag.String("log_level", "info", "logging level: debug/info/warn/error")
flag.Set("alsologtostderr", "true")
flag.Set("stderrthreshold", "INFO")
flag.Set("v", "3")
flag.Parse() flag.Parse()
log.SetLevel("warn")
logger = log.NewLogger(os.Stdout)
wd := util.OS.Pwd() wd := util.OS.Pwd()
if strings.HasPrefix(wd, os.TempDir()) { if strings.HasPrefix(wd, os.TempDir()) {
glog.Error("Don't run wide in OS' temp directory or with `go run`") logger.Error("Don't run wide in OS' temp directory or with `go run`")
os.Exit(-1) os.Exit(-1)
} }
@ -105,7 +108,7 @@ func indexHandler(w http.ResponseWriter, r *http.Request) {
username := httpSession.Values["username"].(string) username := httpSession.Values["username"].(string)
user := conf.Wide.GetUser(username) user := conf.Wide.GetUser(username)
if nil == user { if nil == user {
glog.Warningf("Not found user [%s]", username) logger.Warnf("Not found user [%s]", username)
http.Redirect(w, r, conf.Wide.Context+"login", http.StatusFound) http.Redirect(w, r, conf.Wide.Context+"login", http.StatusFound)
@ -121,12 +124,12 @@ func indexHandler(w http.ResponseWriter, r *http.Request) {
"pathSeparator": conf.PathSeparator, "codeMirrorVer": conf.CodeMirrorVer, "pathSeparator": conf.PathSeparator, "codeMirrorVer": conf.CodeMirrorVer,
"user": user, "editorThemes": conf.GetEditorThemes()} "user": user, "editorThemes": conf.GetEditorThemes()}
glog.V(3).Infof("User [%s] has [%d] sessions", username, len(wideSessions)) logger.Debugf("User [%s] has [%d] sessions", username, len(wideSessions))
t, err := template.ParseFiles("views/index.html") t, err := template.ParseFiles("views/index.html")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -164,7 +167,7 @@ func startHandler(w http.ResponseWriter, r *http.Request) {
sid := r.URL.Query()["sid"][0] sid := r.URL.Query()["sid"][0]
wSession := session.WideSessions.Get(sid) wSession := session.WideSessions.Get(sid)
if nil == wSession { if nil == wSession {
glog.Errorf("Session [%s] not found", sid) logger.Errorf("Session [%s] not found", sid)
} }
model := map[string]interface{}{"conf": conf.Wide, "i18n": i18n.GetAll(locale), "locale": locale, model := map[string]interface{}{"conf": conf.Wide, "i18n": i18n.GetAll(locale), "locale": locale,
@ -173,7 +176,7 @@ func startHandler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("views/start.html") t, err := template.ParseFiles("views/start.html")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -205,7 +208,7 @@ func keyboardShortcutsHandler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("views/keyboard_shortcuts.html") t, err := template.ParseFiles("views/keyboard_shortcuts.html")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -238,7 +241,7 @@ func aboutHandler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("views/about.html") t, err := template.ParseFiles("views/about.html")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -253,8 +256,6 @@ func main() {
initMime() initMime()
defer glog.Flush()
// IDE // IDE
http.HandleFunc(conf.Wide.Context+"/", handlerGzWrapper(indexHandler)) http.HandleFunc(conf.Wide.Context+"/", handlerGzWrapper(indexHandler))
http.HandleFunc(conf.Wide.Context+"/start", handlerWrapper(startHandler)) http.HandleFunc(conf.Wide.Context+"/start", handlerWrapper(startHandler))
@ -321,11 +322,11 @@ func main() {
http.HandleFunc(conf.Wide.Context+"/signup", handlerWrapper(session.SignUpUser)) http.HandleFunc(conf.Wide.Context+"/signup", handlerWrapper(session.SignUpUser))
http.HandleFunc(conf.Wide.Context+"/preference", handlerWrapper(session.PreferenceHandler)) http.HandleFunc(conf.Wide.Context+"/preference", handlerWrapper(session.PreferenceHandler))
glog.Infof("Wide is running [%s]", conf.Wide.Server+conf.Wide.Context) logger.Infof("Wide is running [%s]", conf.Wide.Server+conf.Wide.Context)
err := http.ListenAndServe(conf.Wide.Server, nil) err := http.ListenAndServe(conf.Wide.Server, nil)
if err != nil { if err != nil {
glog.Fatal(err) logger.Error(err)
} }
} }
@ -390,7 +391,7 @@ func stopwatch(handler func(w http.ResponseWriter, r *http.Request)) func(w http
start := time.Now() start := time.Now()
defer func() { defer func() {
glog.V(5).Infof("[%s] [%s]", r.RequestURI, time.Since(start)) logger.Debugf("[%s] [%s]", r.RequestURI, time.Since(start))
}() }()
handler(w, r) handler(w, r)

View File

@ -17,15 +17,16 @@ package notification
import ( import (
"net/http" "net/http"
"os"
"strconv" "strconv"
"time" "time"
"github.com/b3log/wide/conf" "github.com/b3log/wide/conf"
"github.com/b3log/wide/event" "github.com/b3log/wide/event"
"github.com/b3log/wide/i18n" "github.com/b3log/wide/i18n"
"github.com/b3log/wide/log"
"github.com/b3log/wide/session" "github.com/b3log/wide/session"
"github.com/b3log/wide/util" "github.com/b3log/wide/util"
"github.com/golang/glog"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
) )
@ -38,6 +39,9 @@ const (
server = "Server" // notification.type: server server = "Server" // notification.type: server
) )
// Logger.
var logger = log.NewLogger(os.Stdout)
// Notification represents a notification. // Notification represents a notification.
type Notification struct { type Notification struct {
event *event.Event event *event.Event
@ -74,7 +78,7 @@ func event2Notification(e *event.Event) {
notification = &Notification{event: e, Type: server, Severity: error, notification = &Notification{event: e, Type: server, Severity: error,
Message: i18n.Get(locale, "notification_"+strconv.Itoa(e.Code)).(string) + " [" + e.Data.(string) + "]"} Message: i18n.Get(locale, "notification_"+strconv.Itoa(e.Code)).(string) + " [" + e.Data.(string) + "]"}
default: default:
glog.Warningf("Can't handle event[code=%d]", e.Code) logger.Warnf("Can't handle event[code=%d]", e.Code)
return return
} }
@ -105,7 +109,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) {
session.NotificationWS[sid] = &wsChan session.NotificationWS[sid] = &wsChan
glog.V(4).Infof("Open a new [Notification] with session [%s], %d", sid, len(session.NotificationWS)) logger.Debugf("Open a new [Notification] with session [%s], %d", sid, len(session.NotificationWS))
// add user event handler // add user event handler
wSession.EventQueue.AddHandler(event.HandleFunc(event2Notification)) wSession.EventQueue.AddHandler(event.HandleFunc(event2Notification))

View File

@ -32,9 +32,9 @@ import (
"github.com/b3log/wide/conf" "github.com/b3log/wide/conf"
"github.com/b3log/wide/i18n" "github.com/b3log/wide/i18n"
"github.com/b3log/wide/log"
"github.com/b3log/wide/session" "github.com/b3log/wide/session"
"github.com/b3log/wide/util" "github.com/b3log/wide/util"
"github.com/golang/glog"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
) )
@ -43,6 +43,9 @@ const (
lintSeverityWarn = "warning" // lint severity: warning lintSeverityWarn = "warning" // lint severity: warning
) )
// Logger.
var logger = log.NewLogger(os.Stdout)
// Lint represents a code lint. // Lint represents a code lint.
type Lint struct { type Lint struct {
File string `json:"file"` File string `json:"file"`
@ -66,7 +69,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) {
session.OutputWS[sid] = &wsChan session.OutputWS[sid] = &wsChan
glog.V(4).Infof("Open a new [Output] with session [%s], %d", sid, len(session.OutputWS)) logger.Debugf("Open a new [Output] with session [%s], %d", sid, len(session.OutputWS))
} }
// RunHandler handles request of executing a binary file. // RunHandler handles request of executing a binary file.
@ -77,7 +80,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
} }
@ -95,13 +98,13 @@ func RunHandler(w http.ResponseWriter, r *http.Request) {
stdout, err := cmd.StdoutPipe() stdout, err := cmd.StdoutPipe()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
} }
stderr, err := cmd.StderrPipe() stderr, err := cmd.StderrPipe()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
} }
@ -109,7 +112,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) {
errReader := util.NewReader(stderr) errReader := util.NewReader(stderr)
if err := cmd.Start(); nil != err { if err := cmd.Start(); nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
} }
@ -124,7 +127,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) {
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
return return
} }
@ -143,7 +146,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) {
defer util.Recover() defer util.Recover()
defer cmd.Wait() defer cmd.Wait()
glog.V(5).Infof("Session [%s] is running [id=%d, file=%s]", sid, runningId, filePath) logger.Debugf("Session [%s] is running [id=%d, file=%s]", sid, runningId, filePath)
// push once for front-end to get the 'run' state and pid // push once for front-end to get the 'run' state and pid
if nil != wsChannel { if nil != wsChannel {
@ -151,7 +154,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) {
channelRet["output"] = "" channelRet["output"] = ""
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
return return
} }
@ -170,14 +173,14 @@ func RunHandler(w http.ResponseWriter, r *http.Request) {
// remove the exited process from user process set // remove the exited process from user process set
processes.remove(wSession, cmd.Process) processes.remove(wSession, cmd.Process)
glog.V(5).Infof("Session [%s] 's running [id=%d, file=%s] has done [stdout err]", sid, runningId, filePath) logger.Debugf("Session [%s] 's running [id=%d, file=%s] has done [stdout err]", sid, runningId, filePath)
if nil != wsChannel { if nil != wsChannel {
channelRet["cmd"] = "run-done" channelRet["cmd"] = "run-done"
channelRet["output"] = buf channelRet["output"] = buf
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
break break
} }
@ -191,7 +194,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) {
channelRet["output"] = buf channelRet["output"] = buf
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
break break
} }
@ -216,13 +219,13 @@ func RunHandler(w http.ResponseWriter, r *http.Request) {
// remove the exited process from user process set // remove the exited process from user process set
processes.remove(wSession, cmd.Process) processes.remove(wSession, cmd.Process)
glog.V(5).Infof("Session [%s] 's running [id=%d, file=%s] has done [stderr err]", sid, runningId, filePath) logger.Debugf("Session [%s] 's running [id=%d, file=%s] has done [stderr err]", sid, runningId, filePath)
channelRet["cmd"] = "run-done" channelRet["cmd"] = "run-done"
channelRet["output"] = "<span class='stderr'>" + buf + "</span>" channelRet["output"] = "<span class='stderr'>" + buf + "</span>"
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
break break
} }
@ -234,7 +237,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) {
channelRet["output"] = "<span class='stderr'>" + buf + "</span>" channelRet["output"] = "<span class='stderr'>" + buf + "</span>"
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
break break
} }
@ -261,7 +264,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -275,7 +278,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) {
fout, err := os.Create(filePath) fout, err := os.Create(filePath)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -286,7 +289,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) {
fout.WriteString(code) fout.WriteString(code)
if err := fout.Close(); nil != err { if err := fout.Close(); nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -303,13 +306,13 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) {
setCmdEnv(cmd, username) setCmdEnv(cmd, username)
executable := filepath.Base(curDir) + suffix executable := filepath.Base(curDir) + suffix
glog.V(5).Infof("go build for [%s]", executable) logger.Debugf("go build for [%s]", executable)
executable = filepath.Join(curDir, executable) executable = filepath.Join(curDir, executable)
stdout, err := cmd.StdoutPipe() stdout, err := cmd.StdoutPipe()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -317,7 +320,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) {
stderr, err := cmd.StderrPipe() stderr, err := cmd.StderrPipe()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -339,7 +342,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) {
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
return return
} }
@ -349,7 +352,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) {
reader := bufio.NewReader(io.MultiReader(stdout, stderr)) reader := bufio.NewReader(io.MultiReader(stdout, stderr))
if err := cmd.Start(); nil != err { if err := cmd.Start(); nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -359,7 +362,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) {
defer util.Recover() defer util.Recover()
defer cmd.Wait() defer cmd.Wait()
glog.V(5).Infof("Session [%s] is building [id=%d, dir=%s]", sid, runningId, curDir) logger.Debugf("Session [%s] is building [id=%d, dir=%s]", sid, runningId, curDir)
// read all // read all
buf, _ := ioutil.ReadAll(reader) buf, _ := ioutil.ReadAll(reader)
@ -380,7 +383,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) {
out, _ := cmd.CombinedOutput() out, _ := cmd.CombinedOutput()
if len(out) > 0 { if len(out) > 0 {
glog.Warning(string(out)) logger.Warn(string(out))
} }
}() }()
} else { // build error } else { // build error
@ -438,7 +441,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) {
} }
lint := &Lint{ lint := &Lint{
File: filepath.Join(curDir,file), File: filepath.Join(curDir, file),
LineNo: lineNo - 1, LineNo: lineNo - 1,
Severity: lintSeverityError, Severity: lintSeverityError,
Msg: msg, Msg: msg,
@ -451,12 +454,12 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) {
} }
if nil != session.OutputWS[sid] { if nil != session.OutputWS[sid] {
glog.V(5).Infof("Session [%s] 's build [id=%d, dir=%s] has done", sid, runningId, curDir) logger.Debugf("Session [%s] 's build [id=%d, dir=%s] has done", sid, runningId, curDir)
wsChannel := session.OutputWS[sid] wsChannel := session.OutputWS[sid]
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
} }
wsChannel.Refresh() wsChannel.Refresh()
@ -520,7 +523,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -538,7 +541,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) {
stdout, err := cmd.StdoutPipe() stdout, err := cmd.StdoutPipe()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -546,7 +549,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) {
stderr, err := cmd.StderrPipe() stderr, err := cmd.StderrPipe()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -568,7 +571,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) {
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
return return
} }
@ -578,7 +581,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) {
reader := bufio.NewReader(io.MultiReader(stdout, stderr)) reader := bufio.NewReader(io.MultiReader(stdout, stderr))
if err := cmd.Start(); nil != err { if err := cmd.Start(); nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -587,7 +590,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) {
go func(runningId int) { go func(runningId int) {
defer util.Recover() defer util.Recover()
glog.V(5).Infof("Session [%s] is running [go test] [runningId=%d]", sid, runningId) logger.Debugf("Session [%s] is running [go test] [runningId=%d]", sid, runningId)
channelRet := map[string]interface{}{} channelRet := map[string]interface{}{}
channelRet["cmd"] = "go test" channelRet["cmd"] = "go test"
@ -599,11 +602,11 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) {
cmd.Wait() cmd.Wait()
if !cmd.ProcessState.Success() { if !cmd.ProcessState.Success() {
glog.V(5).Infof("Session [%s] 's running [go test] [runningId=%d] has done (with error)", sid, runningId) logger.Debugf("Session [%s] 's running [go test] [runningId=%d] has done (with error)", sid, runningId)
channelRet["output"] = "<span class='test-error'>" + i18n.Get(locale, "test-error").(string) + "</span>\n" + string(buf) channelRet["output"] = "<span class='test-error'>" + i18n.Get(locale, "test-error").(string) + "</span>\n" + string(buf)
} else { } else {
glog.V(5).Infof("Session [%s] 's running [go test] [runningId=%d] has done", sid, runningId) logger.Debugf("Session [%s] 's running [go test] [runningId=%d] has done", sid, runningId)
channelRet["output"] = "<span class='test-succ'>" + i18n.Get(locale, "test-succ").(string) + "</span>\n" + string(buf) channelRet["output"] = "<span class='test-succ'>" + i18n.Get(locale, "test-succ").(string) + "</span>\n" + string(buf)
} }
@ -613,7 +616,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) {
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
} }
wsChannel.Refresh() wsChannel.Refresh()
@ -638,7 +641,7 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -654,11 +657,11 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) {
setCmdEnv(cmd, username) setCmdEnv(cmd, username)
glog.V(5).Infof("go install %s", curDir) logger.Debugf("go install %s", curDir)
stdout, err := cmd.StdoutPipe() stdout, err := cmd.StdoutPipe()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -666,7 +669,7 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) {
stderr, err := cmd.StderrPipe() stderr, err := cmd.StderrPipe()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -688,7 +691,7 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) {
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
return return
} }
@ -698,7 +701,7 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) {
reader := bufio.NewReader(io.MultiReader(stdout, stderr)) reader := bufio.NewReader(io.MultiReader(stdout, stderr))
if err := cmd.Start(); nil != err { if err := cmd.Start(); nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -708,7 +711,7 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) {
defer util.Recover() defer util.Recover()
defer cmd.Wait() defer cmd.Wait()
glog.V(5).Infof("Session [%s] is running [go install] [id=%d, dir=%s]", sid, runningId, curDir) logger.Debugf("Session [%s] is running [go install] [id=%d, dir=%s]", sid, runningId, curDir)
// read all // read all
buf, _ := ioutil.ReadAll(reader) buf, _ := ioutil.ReadAll(reader)
@ -772,12 +775,12 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) {
} }
if nil != session.OutputWS[sid] { if nil != session.OutputWS[sid] {
glog.V(5).Infof("Session [%s] 's running [go install] [id=%d, dir=%s] has done", sid, runningId, curDir) logger.Debugf("Session [%s] 's running [go install] [id=%d, dir=%s] has done", sid, runningId, curDir)
wsChannel := session.OutputWS[sid] wsChannel := session.OutputWS[sid]
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
} }
wsChannel.Refresh() wsChannel.Refresh()
@ -803,7 +806,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -821,7 +824,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) {
stdout, err := cmd.StdoutPipe() stdout, err := cmd.StdoutPipe()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -829,7 +832,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) {
stderr, err := cmd.StderrPipe() stderr, err := cmd.StderrPipe()
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -851,7 +854,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) {
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
return return
} }
@ -861,7 +864,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) {
reader := bufio.NewReader(io.MultiReader(stdout, stderr)) reader := bufio.NewReader(io.MultiReader(stdout, stderr))
if err := cmd.Start(); nil != err { if err := cmd.Start(); nil != err {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -871,7 +874,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) {
defer util.Recover() defer util.Recover()
defer cmd.Wait() defer cmd.Wait()
glog.V(5).Infof("Session [%s] is running [go get] [runningId=%d]", sid, runningId) logger.Debugf("Session [%s] is running [go get] [runningId=%d]", sid, runningId)
channelRet := map[string]interface{}{} channelRet := map[string]interface{}{}
channelRet["cmd"] = "go get" channelRet["cmd"] = "go get"
@ -880,11 +883,11 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) {
buf, _ := ioutil.ReadAll(reader) buf, _ := ioutil.ReadAll(reader)
if 0 != len(buf) { if 0 != len(buf) {
glog.V(5).Infof("Session [%s] 's running [go get] [runningId=%d] has done (with error)", sid, runningId) logger.Debugf("Session [%s] 's running [go get] [runningId=%d] has done (with error)", sid, runningId)
channelRet["output"] = "<span class='get-error'>" + i18n.Get(locale, "get-error").(string) + "</span>\n" + string(buf) channelRet["output"] = "<span class='get-error'>" + i18n.Get(locale, "get-error").(string) + "</span>\n" + string(buf)
} else { } else {
glog.V(5).Infof("Session [%s] 's running [go get] [runningId=%d] has done", sid, runningId) logger.Debugf("Session [%s] 's running [go get] [runningId=%d] has done", sid, runningId)
channelRet["output"] = "<span class='get-succ'>" + i18n.Get(locale, "get-succ").(string) + "</span>\n" channelRet["output"] = "<span class='get-succ'>" + i18n.Get(locale, "get-succ").(string) + "</span>\n"
@ -895,7 +898,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) {
err := wsChannel.WriteJSON(&channelRet) err := wsChannel.WriteJSON(&channelRet)
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
} }
wsChannel.Refresh() wsChannel.Refresh()
@ -910,7 +913,7 @@ func StopHandler(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return

View File

@ -19,7 +19,6 @@ import (
"sync" "sync"
"github.com/b3log/wide/session" "github.com/b3log/wide/session"
"github.com/golang/glog"
) )
// Type of process set. // Type of process set.
@ -47,7 +46,7 @@ func (procs *procs) add(wSession *session.WideSession, proc *os.Process) {
// bind process with wide session // bind process with wide session
wSession.SetProcesses(userProcesses) wSession.SetProcesses(userProcesses)
glog.V(5).Infof("Session [%s] has [%d] processes", sid, len((*procs)[sid])) logger.Debugf("Session [%s] has [%d] processes", sid, len((*procs)[sid]))
} }
// remove removes the specified process from the user process set. // remove removes the specified process from the user process set.
@ -68,7 +67,7 @@ func (procs *procs) remove(wSession *session.WideSession, proc *os.Process) {
// bind process with wide session // bind process with wide session
wSession.SetProcesses(newProcesses) wSession.SetProcesses(newProcesses)
glog.V(5).Infof("Session [%s] has [%d] processes", sid, len((*procs)[sid])) logger.Debugf("Session [%s] has [%d] processes", sid, len((*procs)[sid]))
return return
} }
@ -87,7 +86,7 @@ func (procs *procs) kill(wSession *session.WideSession, pid int) {
for i, p := range userProcesses { for i, p := range userProcesses {
if p.Pid == pid { if p.Pid == pid {
if err := p.Kill(); nil != err { if err := p.Kill(); nil != err {
glog.Error("Kill a process [pid=%d] of session [%s] failed [error=%v]", pid, sid, err) logger.Error("Kill a process [pid=%d] of session [%s] failed [error=%v]", pid, sid, err)
} else { } else {
var newProcesses []*os.Process var newProcesses []*os.Process
@ -97,7 +96,7 @@ func (procs *procs) kill(wSession *session.WideSession, pid int) {
// bind process with wide session // bind process with wide session
wSession.SetProcesses(newProcesses) wSession.SetProcesses(newProcesses)
glog.V(5).Infof("Killed a process [pid=%d] of session [%s]", pid, sid) logger.Debugf("Killed a process [pid=%d] of session [%s]", pid, sid)
} }
return return

View File

@ -33,8 +33,8 @@ import (
"github.com/b3log/wide/conf" "github.com/b3log/wide/conf"
"github.com/b3log/wide/event" "github.com/b3log/wide/event"
"github.com/b3log/wide/log"
"github.com/b3log/wide/util" "github.com/b3log/wide/util"
"github.com/golang/glog"
"github.com/gorilla/sessions" "github.com/gorilla/sessions"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
) )
@ -44,6 +44,9 @@ const (
sessionStateClosed // (not used so far) sessionStateClosed // (not used so far)
) )
// Logger.
var logger = log.NewLogger(os.Stdout)
var ( var (
// SessionWS holds all session channels. <sid, *util.WSChannel> // SessionWS holds all session channels. <sid, *util.WSChannel>
SessionWS = map[string]*util.WSChannel{} SessionWS = map[string]*util.WSChannel{}
@ -97,7 +100,7 @@ func FixedTimeRelease() {
for _, s := range WideSessions { for _, s := range WideSessions {
if s.Updated.Before(threshold) { if s.Updated.Before(threshold) {
glog.V(3).Infof("Removes a invalid session [%s], user [%s]", s.ID, s.Username) logger.Debugf("Removes a invalid session [%s], user [%s]", s.ID, s.Username)
WideSessions.Remove(s.ID) WideSessions.Remove(s.ID)
} }
@ -151,7 +154,7 @@ func FixedTimeReport() {
buf.WriteString(" " + t.report() + "\n") buf.WriteString(" " + t.report() + "\n")
} }
glog.Info(buf.String()) logger.Info(buf.String())
} }
}() }()
} }
@ -174,7 +177,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) {
wSession = WideSessions.New(httpSession, sid) wSession = WideSessions.New(httpSession, sid)
glog.Infof("Created a wide session [%s] for websocket reconnecting, user [%s]", sid, wSession.Username) logger.Infof("Created a wide session [%s] for websocket reconnecting, user [%s]", sid, wSession.Username)
} }
conn, _ := websocket.Upgrade(w, r, nil, 1024, 1024) conn, _ := websocket.Upgrade(w, r, nil, 1024, 1024)
@ -188,13 +191,13 @@ func WSHandler(w http.ResponseWriter, r *http.Request) {
SessionWS[sid] = &wsChan SessionWS[sid] = &wsChan
glog.V(4).Infof("Open a new [Session Channel] with session [%s], %d", sid, len(SessionWS)) logger.Debugf("Open a new [Session Channel] with session [%s], %d", sid, len(SessionWS))
input := map[string]interface{}{} input := map[string]interface{}{}
for { for {
if err := wsChan.ReadJSON(&input); err != nil { if err := wsChan.ReadJSON(&input); err != nil {
glog.V(5).Infof("[Session Channel] of session [%s] disconnected, releases all resources with it, user [%s]", logger.Debugf("[Session Channel] of session [%s] disconnected, releases all resources with it, user [%s]",
sid, wSession.Username) sid, wSession.Username)
WideSessions.Remove(sid) WideSessions.Remove(sid)
@ -205,7 +208,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) {
ret = map[string]interface{}{"output": "", "cmd": "session-output"} ret = map[string]interface{}{"output": "", "cmd": "session-output"}
if err := wsChan.WriteJSON(&ret); err != nil { if err := wsChan.WriteJSON(&ret); err != nil {
glog.Error("Session WS ERROR: " + err.Error()) logger.Error("Session WS ERROR: " + err.Error())
return return
} }
@ -225,7 +228,7 @@ func SaveContent(w http.ResponseWriter, r *http.Request) {
}{} }{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
data["succ"] = false data["succ"] = false
return return
@ -326,9 +329,9 @@ func (sessions *wSessions) Remove(sid string) {
// kill processes // kill processes
for _, p := range s.Processes { for _, p := range s.Processes {
if err := p.Kill(); nil != err { if err := p.Kill(); nil != err {
glog.Errorf("Can't kill process [%d] of session [%s], user [%s]", p.Pid, sid, s.Username) logger.Errorf("Can't kill process [%d] of session [%s], user [%s]", p.Pid, sid, s.Username)
} else { } else {
glog.V(3).Infof("Killed a process [%d] of session [%s], user [%s]", p.Pid, sid, s.Username) logger.Debugf("Killed a process [%d] of session [%s], user [%s]", p.Pid, sid, s.Username)
} }
} }
@ -355,7 +358,7 @@ func (sessions *wSessions) Remove(sid string) {
} }
} }
glog.V(5).Infof("Removed a session [%s] of user [%s], it has [%d] sessions currently", sid, s.Username, cnt) logger.Debugf("Removed a session [%s] of user [%s], it has [%d] sessions currently", sid, s.Username, cnt)
return return
} }

View File

@ -28,7 +28,6 @@ import (
"github.com/b3log/wide/conf" "github.com/b3log/wide/conf"
"github.com/b3log/wide/i18n" "github.com/b3log/wide/i18n"
"github.com/b3log/wide/util" "github.com/b3log/wide/util"
"github.com/golang/glog"
) )
const ( const (
@ -71,7 +70,7 @@ func PreferenceHandler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("views/preference.html") t, err := template.ParseFiles("views/preference.html")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -106,7 +105,7 @@ func PreferenceHandler(w http.ResponseWriter, r *http.Request) {
}{} }{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
succ = false succ = false
return return
@ -142,7 +141,7 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("views/login.html") t, err := template.ParseFiles("views/login.html")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -165,7 +164,7 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) {
}{} }{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
succ = false succ = false
return return
@ -194,7 +193,7 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) {
} }
httpSession.Save(r, w) httpSession.Save(r, w)
glog.Infof("Created a HTTP session [%s] for user [%s]", httpSession.Values["id"].(string), args.Username) logger.Infof("Created a HTTP session [%s] for user [%s]", httpSession.Values["id"].(string), args.Username)
} }
// LogoutHandler handles request of user logout (exit). // LogoutHandler handles request of user logout (exit).
@ -223,7 +222,7 @@ func SignUpUser(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("views/sign_up.html") t, err := template.ParseFiles("views/sign_up.html")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -243,7 +242,7 @@ func SignUpUser(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{} var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil { if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err) logger.Error(err)
succ = false succ = false
return return
@ -298,7 +297,7 @@ func addUser(username, password, email string) string {
http.Handle("/workspace/"+username+"/", http.Handle("/workspace/"+username+"/",
http.StripPrefix("/workspace/"+username+"/", http.FileServer(http.Dir(newUser.GetWorkspace())))) http.StripPrefix("/workspace/"+username+"/", http.FileServer(http.Dir(newUser.GetWorkspace()))))
glog.Infof("Created a user [%s]", username) logger.Infof("Created a user [%s]", username)
return userCreated return userCreated
} }
@ -307,14 +306,14 @@ func addUser(username, password, email string) string {
func helloWorld(workspace string) { func helloWorld(workspace string) {
dir := workspace + conf.PathSeparator + "src" + conf.PathSeparator + "hello" dir := workspace + conf.PathSeparator + "src" + conf.PathSeparator + "hello"
if err := os.MkdirAll(dir, 0755); nil != err { if err := os.MkdirAll(dir, 0755); nil != err {
glog.Error(err) logger.Error(err)
return return
} }
fout, err := os.Create(dir + conf.PathSeparator + "main.go") fout, err := os.Create(dir + conf.PathSeparator + "main.go")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
os.Exit(-1) os.Exit(-1)
} }

View File

@ -28,9 +28,9 @@ import (
"github.com/b3log/wide/conf" "github.com/b3log/wide/conf"
"github.com/b3log/wide/i18n" "github.com/b3log/wide/i18n"
"github.com/b3log/wide/log"
"github.com/b3log/wide/session" "github.com/b3log/wide/session"
"github.com/b3log/wide/util" "github.com/b3log/wide/util"
"github.com/golang/glog"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
) )
@ -39,6 +39,9 @@ import (
// <sid, *util.WSChannel>> // <sid, *util.WSChannel>>
var ShellWS = map[string]*util.WSChannel{} var ShellWS = map[string]*util.WSChannel{}
// Logger.
var logger = log.NewLogger(os.Stdout)
// IndexHandler handles request of Shell index. // IndexHandler handles request of Shell index.
func IndexHandler(w http.ResponseWriter, r *http.Request) { func IndexHandler(w http.ResponseWriter, r *http.Request) {
httpSession, _ := session.HTTPSession.Get(r, "wide-session") httpSession, _ := session.HTTPSession.Get(r, "wide-session")
@ -67,12 +70,12 @@ func IndexHandler(w http.ResponseWriter, r *http.Request) {
wideSessions := session.WideSessions.GetByUsername(username) wideSessions := session.WideSessions.GetByUsername(username)
glog.V(3).Infof("User [%s] has [%d] sessions", username, len(wideSessions)) logger.Debugf("User [%s] has [%d] sessions", username, len(wideSessions))
t, err := template.ParseFiles("views/shell.html") t, err := template.ParseFiles("views/shell.html")
if nil != err { if nil != err {
glog.Error(err) logger.Error(err)
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
@ -104,13 +107,13 @@ func WSHandler(w http.ResponseWriter, r *http.Request) {
ShellWS[sid] = &wsChan ShellWS[sid] = &wsChan
glog.V(4).Infof("Open a new [Shell] with session [%s], %d", sid, len(ShellWS)) logger.Debugf("Open a new [Shell] with session [%s], %d", sid, len(ShellWS))
input := map[string]interface{}{} input := map[string]interface{}{}
for { for {
if err := wsChan.ReadJSON(&input); err != nil { if err := wsChan.ReadJSON(&input); err != nil {
glog.Error("Shell WS ERROR: " + err.Error()) logger.Error("Shell WS ERROR: " + err.Error())
return return
} }
@ -139,7 +142,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) {
ret = map[string]interface{}{"output": output, "cmd": "shell-output"} ret = map[string]interface{}{"output": output, "cmd": "shell-output"}
if err := wsChan.WriteJSON(&ret); err != nil { if err := wsChan.WriteJSON(&ret); err != nil {
glog.Error("Shell WS ERROR: " + err.Error()) logger.Error("Shell WS ERROR: " + err.Error())
return return
} }

View File

@ -18,9 +18,12 @@ import (
"os" "os"
"strings" "strings"
"github.com/golang/glog" "github.com/b3log/wide/log"
) )
// Logger.
var fileLogger = log.NewLogger(os.Stdout)
type myfile struct{} type myfile struct{}
// File utilities. // File utilities.
@ -70,7 +73,7 @@ func (*myfile) IsImg(extension string) bool {
func (*myfile) IsDir(path string) bool { func (*myfile) IsDir(path string) bool {
fio, err := os.Lstat(path) fio, err := os.Lstat(path)
if nil != err { if nil != err {
glog.Warningf("Determines whether [%s] is a directory failed: [%v]", path, err) fileLogger.Warnf("Determines whether [%s] is a directory failed: [%v]", path, err)
return false return false
} }

View File

@ -15,14 +15,18 @@
package util package util
import ( import (
"os"
"runtime/debug" "runtime/debug"
"github.com/golang/glog" "github.com/b3log/wide/log"
) )
// Logger.
var logger = log.NewLogger(os.Stdout)
// Recover recovers a panic. // Recover recovers a panic.
func Recover() { func Recover() {
if re := recover(); nil != re { if re := recover(); nil != re {
glog.Errorf("PANIC RECOVERED:\n %v, %s", re, debug.Stack()) logger.Errorf("PANIC RECOVERED:\n %v, %s", re, debug.Stack())
} }
} }

View File

@ -18,17 +18,21 @@ import (
"compress/gzip" "compress/gzip"
"encoding/json" "encoding/json"
"net/http" "net/http"
"os"
"github.com/golang/glog" "github.com/b3log/wide/log"
) )
// Logger.
var retLogger = log.NewLogger(os.Stdout)
// RetJSON writes HTTP response with "Content-Type, application/json". // RetJSON writes HTTP response with "Content-Type, application/json".
func RetJSON(w http.ResponseWriter, r *http.Request, res map[string]interface{}) { func RetJSON(w http.ResponseWriter, r *http.Request, res map[string]interface{}) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
data, err := json.Marshal(res) data, err := json.Marshal(res)
if err != nil { if err != nil {
glog.Error(err) retLogger.Error(err)
return return
} }
@ -43,13 +47,13 @@ func RetGzJSON(w http.ResponseWriter, r *http.Request, res map[string]interface{
gz := gzip.NewWriter(w) gz := gzip.NewWriter(w)
err := json.NewEncoder(gz).Encode(res) err := json.NewEncoder(gz).Encode(res)
if nil != err { if nil != err {
glog.Error(err) retLogger.Error(err)
return return
} }
err = gz.Close() err = gz.Close()
if nil != err { if nil != err {
glog.Error(err) retLogger.Error(err)
return return
} }