From cb14485388df1c3db1a19f940fe2a351fd87f128 Mon Sep 17 00:00:00 2001 From: Liang Ding Date: Sat, 13 Dec 2014 18:47:41 +0800 Subject: [PATCH] new logging --- conf/wide.go | 46 +++++++------- conf/wide.json | 1 + editor/editors.go | 53 ++++++++-------- editor/formatter.go | 9 ++- event/events.go | 15 +++-- file/exporter.go | 5 +- file/files.go | 57 +++++++++-------- i18n/locales.go | 11 ++-- log/logs.go | 57 +++++++++++++++-- main.go | 37 +++++------ notification/notifications.go | 10 ++- output/outputs.go | 115 +++++++++++++++++----------------- output/processes.go | 9 ++- session/sessions.go | 25 ++++---- session/users.go | 21 +++---- shell/shells.go | 15 +++-- util/file.go | 13 ++-- util/panic.go | 8 ++- util/ret.go | 12 ++-- 19 files changed, 304 insertions(+), 215 deletions(-) diff --git a/conf/wide.go b/conf/wide.go index 7f6c679..8ec9492 100644 --- a/conf/wide.go +++ b/conf/wide.go @@ -29,8 +29,8 @@ import ( "time" "github.com/b3log/wide/event" + "github.com/b3log/wide/log" "github.com/b3log/wide/util" - "github.com/golang/glog" ) const ( @@ -93,6 +93,7 @@ type conf struct { Context string // server context Server string // server host and port ({IP}:{Port}) StaticServer string // static resources server scheme, host and port (http://{IP}:{Port}) + LogLevel string // logging level Channel string // channel (ws://{IP}:{Port}) HTTPSessionMaxAge int // HTTP session max age (in seciond) StaticResourceVersion string // version of static resources @@ -111,6 +112,9 @@ var Wide conf // Save function will use this variable to persist. var rawWide conf +// Logger. +var logger = log.NewLogger(os.Stdout) + // FixedTimeCheckEnv checks Wide runtime enviorment periodically (7 minutes). // // Exits process if found fatal issues (such as not found $GOPATH), @@ -129,14 +133,14 @@ func checkEnv() { cmd := exec.Command("go", "version") buf, err := cmd.CombinedOutput() 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) } - glog.V(5).Info(string(buf)) + logger.Debug(string(buf)) 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) } @@ -147,7 +151,7 @@ func checkEnv() { if nil != err { 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") @@ -156,7 +160,7 @@ func checkEnv() { if nil != err { 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": return util.Go.GetExecutableInGOBIN("goimports") default: - glog.Errorf("Unsupported Go Format tool [%s]", user.GoFormat) + logger.Errorf("Unsupported Go Format tool [%s]", user.GoFormat) return "gofmt" } } @@ -234,13 +238,13 @@ func Save() bool { bytes, err := json.MarshalIndent(rawWide, "", " ") if nil != err { - glog.Error(err) + logger.Error(err) return false } if err = ioutil.WriteFile("conf/wide.json", bytes, 0644); nil != err { - glog.Error(err) + logger.Error(err) return false } @@ -254,29 +258,31 @@ func Load(confPath, confIP, confPort, confServer, confStaticServer, confContext, err := json.Unmarshal(bytes, &Wide) if err != nil { - glog.Error("Parses wide.json error: ", err) + logger.Error("Parses wide.json error: ", err) os.Exit(-1) } + log.SetLevel(Wide.LogLevel) + // keep the raw content json.Unmarshal(bytes, &rawWide) - glog.V(5).Info("Conf: \n" + string(bytes)) + logger.Debug("Conf: \n" + string(bytes)) // Working Driectory Wide.WD = util.OS.Pwd() - glog.V(5).Infof("${pwd} [%s]", Wide.WD) + logger.Debugf("${pwd} [%s]", Wide.WD) // IP ip, err := util.Net.LocalIP() if err != nil { - glog.Error(err) + logger.Error(err) os.Exit(-1) } - glog.V(5).Infof("${ip} [%s]", ip) + logger.Debugf("${ip} [%s]", ip) if confDocker { // 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") if nil != err { - glog.Error(err) + logger.Error(err) os.Exit(-1) } @@ -382,14 +388,14 @@ func UpdateCustomizedConf(username string) { wd := util.OS.Pwd() dir := filepath.Clean(wd + "/static/user/" + u.Name) if err := os.MkdirAll(dir, 0755); nil != err { - glog.Error(err) + logger.Error(err) os.Exit(-1) } fout, err := os.Create(dir + PathSeparator + "style.css") if nil != err { - glog.Error(err) + logger.Error(err) os.Exit(-1) } @@ -397,7 +403,7 @@ func UpdateCustomizedConf(username string) { defer fout.Close() if err := t.Execute(fout, model); nil != err { - glog.Error(err) + logger.Error(err) os.Exit(-1) } @@ -435,12 +441,10 @@ func CreateWorkspaceDir(path string) { func createDir(path string) { if !util.File.IsExist(path) { if err := os.MkdirAll(path, 0775); nil != err { - glog.Error(err) + logger.Error(err) os.Exit(-1) } - - glog.V(7).Infof("Created a directory [%s]", path) } } diff --git a/conf/wide.json b/conf/wide.json index 436274c..696eac3 100644 --- a/conf/wide.json +++ b/conf/wide.json @@ -4,6 +4,7 @@ "Context": "", "Server": "{IP}:{Port}", "StaticServer": "", + "LogLevel": "info", "Channel": "ws://{IP}:{Port}", "HTTPSessionMaxAge": 86400, "StaticResourceVersion": "${time}", diff --git a/editor/editors.go b/editor/editors.go index 044b6ca..b485f0a 100644 --- a/editor/editors.go +++ b/editor/editors.go @@ -29,12 +29,15 @@ import ( "github.com/b3log/wide/conf" "github.com/b3log/wide/file" + "github.com/b3log/wide/log" "github.com/b3log/wide/session" "github.com/b3log/wide/util" - "github.com/golang/glog" "github.com/gorilla/websocket" ) +// Logger. +var logger = log.NewLogger(os.Stdout) + // WSHandler handles request of creating editor channel. // XXX: NOT used at present func WSHandler(w http.ResponseWriter, r *http.Request) { @@ -58,7 +61,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) { 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{}{} for { @@ -72,7 +75,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) { offset := getCursorOffset(code, line, ch) - // glog.Infof("offset: %d", offset) + // logger.Infof("offset: %d", offset) gocode := util.Go.GetExecutableInGOBIN("gocode") 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"} if err := session.EditorWS[sid].WriteJSON(&ret); err != nil { - glog.Error("Editor WS ERROR: " + err.Error()) + logger.Error("Editor WS ERROR: " + err.Error()) return } } @@ -102,7 +105,7 @@ func AutocompleteHandler(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -121,7 +124,7 @@ func AutocompleteHandler(w http.ResponseWriter, r *http.Request) { fout, err := os.Create(path) if nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -131,7 +134,7 @@ func AutocompleteHandler(w http.ResponseWriter, r *http.Request) { fout.WriteString(code) if err := fout.Close(); nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -142,7 +145,7 @@ func AutocompleteHandler(w http.ResponseWriter, r *http.Request) { offset := getCursorOffset(code, line, ch) - // glog.Infof("offset: %d", offset) + // logger.Infof("offset: %d", offset) userWorkspace := conf.Wide.GetUserWorkspace(username) workspaces := filepath.SplitList(userWorkspace) @@ -153,7 +156,7 @@ func AutocompleteHandler(w http.ResponseWriter, r *http.Request) { 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 gocode := util.Go.GetExecutableInGOBIN("gocode") @@ -169,7 +172,7 @@ func AutocompleteHandler(w http.ResponseWriter, r *http.Request) { output, err := cmd.CombinedOutput() if nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -189,7 +192,7 @@ func GetExprInfoHandler(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -202,7 +205,7 @@ func GetExprInfoHandler(w http.ResponseWriter, r *http.Request) { fout, err := os.Create(path) if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -212,7 +215,7 @@ func GetExprInfoHandler(w http.ResponseWriter, r *http.Request) { fout.WriteString(code) if err := fout.Close(); nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -223,7 +226,7 @@ func GetExprInfoHandler(w http.ResponseWriter, r *http.Request) { offset := getCursorOffset(code, line, ch) - // glog.Infof("offset [%d]", offset) + // logger.Infof("offset [%d]", offset) ideStub := util.Go.GetExecutableInGOBIN("ide_stub") 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() if nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -265,7 +268,7 @@ func FindDeclarationHandler(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -278,7 +281,7 @@ func FindDeclarationHandler(w http.ResponseWriter, r *http.Request) { fout, err := os.Create(path) if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -288,7 +291,7 @@ func FindDeclarationHandler(w http.ResponseWriter, r *http.Request) { fout.WriteString(code) if err := fout.Close(); nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -299,7 +302,7 @@ func FindDeclarationHandler(w http.ResponseWriter, r *http.Request) { offset := getCursorOffset(code, line, ch) - // glog.Infof("offset [%d]", offset) + // logger.Infof("offset [%d]", offset) ideStub := util.Go.GetExecutableInGOBIN("ide_stub") 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() if nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -350,7 +353,7 @@ func FindUsagesHandler(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -363,7 +366,7 @@ func FindUsagesHandler(w http.ResponseWriter, r *http.Request) { fout, err := os.Create(filePath) if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -373,7 +376,7 @@ func FindUsagesHandler(w http.ResponseWriter, r *http.Request) { fout.WriteString(code) if err := fout.Close(); nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -383,7 +386,7 @@ func FindUsagesHandler(w http.ResponseWriter, r *http.Request) { ch := int(args["cursorCh"].(float64)) offset := getCursorOffset(code, line, ch) - // glog.Infof("offset [%d]", offset) + // logger.Infof("offset [%d]", offset) ideStub := util.Go.GetExecutableInGOBIN("ide_stub") 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() if nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return diff --git a/editor/formatter.go b/editor/formatter.go index 945375b..dd89421 100644 --- a/editor/formatter.go +++ b/editor/formatter.go @@ -23,7 +23,6 @@ import ( "github.com/b3log/wide/conf" "github.com/b3log/wide/session" "github.com/b3log/wide/util" - "github.com/golang/glog" ) // 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{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -62,7 +61,7 @@ func GoFmtHandler(w http.ResponseWriter, r *http.Request) { fout, err := os.Create(filePath) if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -72,7 +71,7 @@ func GoFmtHandler(w http.ResponseWriter, r *http.Request) { fout.WriteString(code) if err := fout.Close(); nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -99,7 +98,7 @@ func GoFmtHandler(w http.ResponseWriter, r *http.Request) { fout, err = os.Create(filePath) fout.WriteString(code) if err := fout.Close(); nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return diff --git a/event/events.go b/event/events.go index 74a0878..2bcab64 100644 --- a/event/events.go +++ b/event/events.go @@ -15,7 +15,11 @@ // Package event includes event related manipulations. package event -import "github.com/golang/glog" +import ( + "os" + + "github.com/b3log/wide/log" +) const ( // EvtCodeGOPATHNotFound indicates an event: not found $GOPATH env variable @@ -33,6 +37,9 @@ const ( // Max length of queue. const maxQueueLength = 10 +// Logger. +var logger = log.NewLogger(os.Stdout) + // Event represents an event. type Event struct { Code int `json:"code"` // event code @@ -63,7 +70,7 @@ var UserEventQueues = queues{} func Load() { go func() { 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 for _, userQueue := range UserEventQueues { @@ -86,7 +93,7 @@ func (uq *UserEventQueue) AddHandler(handlers ...Handler) { func (ueqs queues) New(sid string) *UserEventQueue { q := ueqs[sid] 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 } @@ -100,7 +107,7 @@ func (ueqs queues) New(sid string) *UserEventQueue { go func() { // start listening 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 for _, handler := range q.Handlers { diff --git a/file/exporter.go b/file/exporter.go index d69703a..78c0343 100644 --- a/file/exporter.go +++ b/file/exporter.go @@ -21,7 +21,6 @@ import ( "path/filepath" "github.com/b3log/wide/util" - "github.com/golang/glog" ) // GetZip handles request of retrieving zip file. @@ -57,7 +56,7 @@ func CreateZip(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -75,7 +74,7 @@ func CreateZip(w http.ResponseWriter, r *http.Request) { zipFile, err := util.Zip.Create(path + ".zip") if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return diff --git a/file/files.go b/file/files.go index 17b1416..e4498f9 100644 --- a/file/files.go +++ b/file/files.go @@ -26,11 +26,14 @@ import ( "github.com/b3log/wide/conf" "github.com/b3log/wide/event" + "github.com/b3log/wide/log" "github.com/b3log/wide/session" "github.com/b3log/wide/util" - "github.com/golang/glog" ) +// Logger. +var logger = log.NewLogger(os.Stdout) + // Node represents a file node in file tree. type Node struct { Name string `json:"name"` @@ -120,7 +123,7 @@ func RefreshDirectory(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") data, err := json.Marshal(node.Children) if err != nil { - glog.Error(err) + logger.Error(err) return } @@ -135,7 +138,7 @@ func GetFile(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -162,7 +165,7 @@ func GetFile(w http.ResponseWriter, r *http.Request) { user := GetUsre(path) if nil == user { - glog.Warningf("The path [%s] has no owner") + logger.Warnf("The path [%s] has no owner") data["path"] = "" return @@ -193,7 +196,7 @@ func SaveFile(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -205,7 +208,7 @@ func SaveFile(w http.ResponseWriter, r *http.Request) { fout, err := os.Create(filePath) if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -216,7 +219,7 @@ func SaveFile(w http.ResponseWriter, r *http.Request) { fout.WriteString(code) if err := fout.Close(); nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false wSession := session.WideSessions.Get(sid) @@ -235,7 +238,7 @@ func NewFile(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -270,7 +273,7 @@ func RemoveFile(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -297,7 +300,7 @@ func RenameFile(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -336,7 +339,7 @@ func Find(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -385,7 +388,7 @@ func SearchText(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -429,7 +432,7 @@ func walk(path string, node *Node, creatable, removable bool) { node.Children = append(node.Children, &child) if nil == fio { - glog.Warningf("Path [%s] is nil", fpath) + logger.Warnf("Path [%s] is nil", fpath) continue } @@ -471,7 +474,7 @@ func listFiles(dirname string) []string { fio, err := os.Lstat(path) if nil != err { - glog.Warningf("Can't read file info [%s]", path) + logger.Warnf("Can't read file info [%s]", path) continue } @@ -562,30 +565,30 @@ func createFile(path, fileType string) bool { case "f": file, err := os.OpenFile(path, os.O_CREATE, 0775) if nil != err { - glog.Error(err) + logger.Error(err) return false } defer file.Close() - glog.V(5).Infof("Created file [%s]", path) + logger.Debugf("Created file [%s]", path) return true case "d": err := os.Mkdir(path, 0775) if nil != err { - glog.Error(err) + logger.Error(err) return false } - glog.V(5).Infof("Created directory [%s]", path) + logger.Debugf("Created directory [%s]", path) return true default: - glog.Errorf("Unsupported file type [%s]", fileType) + logger.Errorf("Unsupported file type [%s]", fileType) return false } @@ -594,12 +597,12 @@ func createFile(path, fileType string) bool { // removeFile removes file on the specified path. func removeFile(path string) bool { 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 } - glog.V(5).Infof("Removed [%s]", path) + logger.Debugf("Removed [%s]", path) 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. func renameFile(oldPath, newPath string) bool { 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 } - glog.V(5).Infof("Renamed [%s] to [%s]", oldPath, newPath) + logger.Debugf("Renamed [%s] to [%s]", oldPath, newPath) return true } @@ -632,7 +635,7 @@ func find(dir, name string, results []*string) []*string { f.Close() 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 } @@ -655,7 +658,7 @@ func find(dir, name string, results []*string) []*string { match, err := filepath.Match(strings.ToLower(pattern), strings.ToLower(path)) if nil != err { - glog.Errorf("Find match filename failed: [%s]", err.Error) + logger.Errorf("Find match filename failed: [%s]", err.Error) continue } @@ -681,7 +684,7 @@ func search(dir, extension, text string, snippets []*Snippet) []*Snippet { f.Close() 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 } @@ -709,7 +712,7 @@ func searchInFile(path string, text string) []*Snippet { bytes, err := ioutil.ReadFile(path) 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 } diff --git a/i18n/locales.go b/i18n/locales.go index 89c7814..f5337cf 100644 --- a/i18n/locales.go +++ b/i18n/locales.go @@ -22,9 +22,12 @@ import ( "sort" "strings" - "github.com/golang/glog" + "github.com/b3log/wide/log" ) +// Logger. +var logger = log.NewLogger(os.Stdout) + // Locale. type locale struct { Name string @@ -54,7 +57,7 @@ func Load() { func load(localeStr string) { bytes, err := ioutil.ReadFile("i18n/" + localeStr + ".json") if nil != err { - glog.Error(err) + logger.Error(err) os.Exit(-1) } @@ -63,14 +66,14 @@ func load(localeStr string) { err = json.Unmarshal(bytes, &l.Langs) if nil != err { - glog.Error(err) + logger.Error(err) os.Exit(-1) } 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. diff --git a/log/logs.go b/log/logs.go index 47e4dbb..ea90c40 100755 --- a/log/logs.go +++ b/log/logs.go @@ -14,7 +14,8 @@ // 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.Info("info message") @@ -28,6 +29,7 @@ import ( "fmt" "io" stdlog "log" + "strings" ) // Logging level. @@ -38,20 +40,65 @@ const ( Error ) -// Logger is a simple logger with level. -// The underlying logger is the Go standard logging "log". +// all loggers. +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 { level int logger *stdlog.Logger } // NewLogger creates a logger. -func NewLogger(out io.Writer, level int) *Logger { - ret := &Logger{level: level, logger: stdlog.New(out, "", stdlog.Ldate|stdlog.Ltime|stdlog.Lshortfile)} +func NewLogger(out io.Writer) *Logger { + ret := &Logger{level: logLevel, logger: stdlog.New(out, "", stdlog.Ldate|stdlog.Ltime|stdlog.Lshortfile)} + + loggers = append(loggers, 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. func (l *Logger) Debug(v ...interface{}) { if Debug < l.level { diff --git a/main.go b/main.go index b264ff8..d4fc24f 100644 --- a/main.go +++ b/main.go @@ -33,14 +33,17 @@ import ( "github.com/b3log/wide/event" "github.com/b3log/wide/file" "github.com/b3log/wide/i18n" + "github.com/b3log/wide/log" "github.com/b3log/wide/notification" "github.com/b3log/wide/output" "github.com/b3log/wide/session" "github.com/b3log/wide/shell" "github.com/b3log/wide/util" - "github.com/golang/glog" ) +// Logger +var logger *log.Logger + // The only one init function in Wide. func init() { 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") confStat := flag.Bool("stat", false, "whether report statistics periodically") confDocker := flag.Bool("docker", false, "whether run in a docker container") - - flag.Set("alsologtostderr", "true") - flag.Set("stderrthreshold", "INFO") - flag.Set("v", "3") + // confLogLevel := flag.String("log_level", "info", "logging level: debug/info/warn/error") flag.Parse() + log.SetLevel("warn") + logger = log.NewLogger(os.Stdout) + wd := util.OS.Pwd() 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) } @@ -105,7 +108,7 @@ func indexHandler(w http.ResponseWriter, r *http.Request) { username := httpSession.Values["username"].(string) user := conf.Wide.GetUser(username) 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) @@ -121,12 +124,12 @@ func indexHandler(w http.ResponseWriter, r *http.Request) { "pathSeparator": conf.PathSeparator, "codeMirrorVer": conf.CodeMirrorVer, "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") if nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -164,7 +167,7 @@ func startHandler(w http.ResponseWriter, r *http.Request) { sid := r.URL.Query()["sid"][0] wSession := session.WideSessions.Get(sid) 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, @@ -173,7 +176,7 @@ func startHandler(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles("views/start.html") if nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -205,7 +208,7 @@ func keyboardShortcutsHandler(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles("views/keyboard_shortcuts.html") if nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -238,7 +241,7 @@ func aboutHandler(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles("views/about.html") if nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -253,8 +256,6 @@ func main() { initMime() - defer glog.Flush() - // IDE http.HandleFunc(conf.Wide.Context+"/", handlerGzWrapper(indexHandler)) 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+"/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) 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() 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) diff --git a/notification/notifications.go b/notification/notifications.go index ecb79c4..68b9772 100644 --- a/notification/notifications.go +++ b/notification/notifications.go @@ -17,15 +17,16 @@ package notification import ( "net/http" + "os" "strconv" "time" "github.com/b3log/wide/conf" "github.com/b3log/wide/event" "github.com/b3log/wide/i18n" + "github.com/b3log/wide/log" "github.com/b3log/wide/session" "github.com/b3log/wide/util" - "github.com/golang/glog" "github.com/gorilla/websocket" ) @@ -38,6 +39,9 @@ const ( server = "Server" // notification.type: server ) +// Logger. +var logger = log.NewLogger(os.Stdout) + // Notification represents a notification. type Notification struct { event *event.Event @@ -74,7 +78,7 @@ func event2Notification(e *event.Event) { notification = &Notification{event: e, Type: server, Severity: error, Message: i18n.Get(locale, "notification_"+strconv.Itoa(e.Code)).(string) + " [" + e.Data.(string) + "]"} default: - glog.Warningf("Can't handle event[code=%d]", e.Code) + logger.Warnf("Can't handle event[code=%d]", e.Code) return } @@ -105,7 +109,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) { 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 wSession.EventQueue.AddHandler(event.HandleFunc(event2Notification)) diff --git a/output/outputs.go b/output/outputs.go index ff93f09..1def94e 100644 --- a/output/outputs.go +++ b/output/outputs.go @@ -32,9 +32,9 @@ import ( "github.com/b3log/wide/conf" "github.com/b3log/wide/i18n" + "github.com/b3log/wide/log" "github.com/b3log/wide/session" "github.com/b3log/wide/util" - "github.com/golang/glog" "github.com/gorilla/websocket" ) @@ -43,6 +43,9 @@ const ( lintSeverityWarn = "warning" // lint severity: warning ) +// Logger. +var logger = log.NewLogger(os.Stdout) + // Lint represents a code lint. type Lint struct { File string `json:"file"` @@ -66,7 +69,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) { 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. @@ -77,7 +80,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false } @@ -95,13 +98,13 @@ func RunHandler(w http.ResponseWriter, r *http.Request) { stdout, err := cmd.StdoutPipe() if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false } stderr, err := cmd.StderrPipe() if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false } @@ -109,7 +112,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) { errReader := util.NewReader(stderr) if err := cmd.Start(); nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false } @@ -124,7 +127,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) { err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) return } @@ -143,7 +146,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) { defer util.Recover() 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 if nil != wsChannel { @@ -151,7 +154,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) { channelRet["output"] = "" err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) return } @@ -170,14 +173,14 @@ func RunHandler(w http.ResponseWriter, r *http.Request) { // remove the exited process from user process set 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 { channelRet["cmd"] = "run-done" channelRet["output"] = buf err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) break } @@ -191,7 +194,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) { channelRet["output"] = buf err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) break } @@ -216,13 +219,13 @@ func RunHandler(w http.ResponseWriter, r *http.Request) { // remove the exited process from user process set 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["output"] = "" + buf + "" err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) break } @@ -234,7 +237,7 @@ func RunHandler(w http.ResponseWriter, r *http.Request) { channelRet["output"] = "" + buf + "" err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) break } @@ -261,7 +264,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -275,7 +278,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) { fout, err := os.Create(filePath) if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -286,7 +289,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) { fout.WriteString(code) if err := fout.Close(); nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -303,13 +306,13 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) { setCmdEnv(cmd, username) 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) stdout, err := cmd.StdoutPipe() if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -317,7 +320,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) { stderr, err := cmd.StderrPipe() if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -339,7 +342,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) { err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) return } @@ -349,7 +352,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) { reader := bufio.NewReader(io.MultiReader(stdout, stderr)) if err := cmd.Start(); nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -359,7 +362,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) { defer util.Recover() 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 buf, _ := ioutil.ReadAll(reader) @@ -380,7 +383,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) { out, _ := cmd.CombinedOutput() if len(out) > 0 { - glog.Warning(string(out)) + logger.Warn(string(out)) } }() } else { // build error @@ -438,7 +441,7 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) { } lint := &Lint{ - File: filepath.Join(curDir,file), + File: filepath.Join(curDir, file), LineNo: lineNo - 1, Severity: lintSeverityError, Msg: msg, @@ -451,12 +454,12 @@ func BuildHandler(w http.ResponseWriter, r *http.Request) { } 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] err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) } wsChannel.Refresh() @@ -520,7 +523,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -538,7 +541,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) { stdout, err := cmd.StdoutPipe() if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -546,7 +549,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) { stderr, err := cmd.StderrPipe() if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -568,7 +571,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) { err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) return } @@ -578,7 +581,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) { reader := bufio.NewReader(io.MultiReader(stdout, stderr)) if err := cmd.Start(); nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -587,7 +590,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) { go func(runningId int) { 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["cmd"] = "go test" @@ -599,11 +602,11 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) { cmd.Wait() 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"] = "" + i18n.Get(locale, "test-error").(string) + "\n" + string(buf) } 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"] = "" + i18n.Get(locale, "test-succ").(string) + "\n" + string(buf) } @@ -613,7 +616,7 @@ func GoTestHandler(w http.ResponseWriter, r *http.Request) { err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) } wsChannel.Refresh() @@ -638,7 +641,7 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -654,11 +657,11 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) { setCmdEnv(cmd, username) - glog.V(5).Infof("go install %s", curDir) + logger.Debugf("go install %s", curDir) stdout, err := cmd.StdoutPipe() if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -666,7 +669,7 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) { stderr, err := cmd.StderrPipe() if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -688,7 +691,7 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) { err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) return } @@ -698,7 +701,7 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) { reader := bufio.NewReader(io.MultiReader(stdout, stderr)) if err := cmd.Start(); nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -708,7 +711,7 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) { defer util.Recover() 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 buf, _ := ioutil.ReadAll(reader) @@ -772,12 +775,12 @@ func GoInstallHandler(w http.ResponseWriter, r *http.Request) { } 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] err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) } wsChannel.Refresh() @@ -803,7 +806,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -821,7 +824,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) { stdout, err := cmd.StdoutPipe() if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -829,7 +832,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) { stderr, err := cmd.StderrPipe() if nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -851,7 +854,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) { err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) return } @@ -861,7 +864,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) { reader := bufio.NewReader(io.MultiReader(stdout, stderr)) if err := cmd.Start(); nil != err { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -871,7 +874,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) { defer util.Recover() 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["cmd"] = "go get" @@ -880,11 +883,11 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) { buf, _ := ioutil.ReadAll(reader) 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"] = "" + i18n.Get(locale, "get-error").(string) + "\n" + string(buf) } 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"] = "" + i18n.Get(locale, "get-succ").(string) + "\n" @@ -895,7 +898,7 @@ func GoGetHandler(w http.ResponseWriter, r *http.Request) { err := wsChannel.WriteJSON(&channelRet) if nil != err { - glog.Error(err) + logger.Error(err) } wsChannel.Refresh() @@ -910,7 +913,7 @@ func StopHandler(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return diff --git a/output/processes.go b/output/processes.go index f25b380..88ec622 100644 --- a/output/processes.go +++ b/output/processes.go @@ -19,7 +19,6 @@ import ( "sync" "github.com/b3log/wide/session" - "github.com/golang/glog" ) // Type of process set. @@ -47,7 +46,7 @@ func (procs *procs) add(wSession *session.WideSession, proc *os.Process) { // bind process with wide session 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. @@ -68,7 +67,7 @@ func (procs *procs) remove(wSession *session.WideSession, proc *os.Process) { // bind process with wide session 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 } @@ -87,7 +86,7 @@ func (procs *procs) kill(wSession *session.WideSession, pid int) { for i, p := range userProcesses { if p.Pid == pid { 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 { var newProcesses []*os.Process @@ -97,7 +96,7 @@ func (procs *procs) kill(wSession *session.WideSession, pid int) { // bind process with wide session 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 diff --git a/session/sessions.go b/session/sessions.go index 52697ab..594b2d5 100644 --- a/session/sessions.go +++ b/session/sessions.go @@ -33,8 +33,8 @@ import ( "github.com/b3log/wide/conf" "github.com/b3log/wide/event" + "github.com/b3log/wide/log" "github.com/b3log/wide/util" - "github.com/golang/glog" "github.com/gorilla/sessions" "github.com/gorilla/websocket" ) @@ -44,6 +44,9 @@ const ( sessionStateClosed // (not used so far) ) +// Logger. +var logger = log.NewLogger(os.Stdout) + var ( // SessionWS holds all session channels. SessionWS = map[string]*util.WSChannel{} @@ -97,7 +100,7 @@ func FixedTimeRelease() { for _, s := range WideSessions { 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) } @@ -151,7 +154,7 @@ func FixedTimeReport() { 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) - 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) @@ -188,13 +191,13 @@ func WSHandler(w http.ResponseWriter, r *http.Request) { 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{}{} for { 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) WideSessions.Remove(sid) @@ -205,7 +208,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) { ret = map[string]interface{}{"output": "", "cmd": "session-output"} if err := wsChan.WriteJSON(&ret); err != nil { - glog.Error("Session WS ERROR: " + err.Error()) + logger.Error("Session WS ERROR: " + err.Error()) return } @@ -225,7 +228,7 @@ func SaveContent(w http.ResponseWriter, r *http.Request) { }{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) data["succ"] = false return @@ -326,9 +329,9 @@ func (sessions *wSessions) Remove(sid string) { // kill processes for _, p := range s.Processes { 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 { - 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 } diff --git a/session/users.go b/session/users.go index 70c6d9f..cd3e7c2 100644 --- a/session/users.go +++ b/session/users.go @@ -28,7 +28,6 @@ import ( "github.com/b3log/wide/conf" "github.com/b3log/wide/i18n" "github.com/b3log/wide/util" - "github.com/golang/glog" ) const ( @@ -71,7 +70,7 @@ func PreferenceHandler(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles("views/preference.html") if nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -106,7 +105,7 @@ func PreferenceHandler(w http.ResponseWriter, r *http.Request) { }{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) succ = false return @@ -142,7 +141,7 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles("views/login.html") if nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -165,7 +164,7 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) { }{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) succ = false return @@ -194,7 +193,7 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) { } 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). @@ -223,7 +222,7 @@ func SignUpUser(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles("views/sign_up.html") if nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -243,7 +242,7 @@ func SignUpUser(w http.ResponseWriter, r *http.Request) { var args map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&args); err != nil { - glog.Error(err) + logger.Error(err) succ = false return @@ -298,7 +297,7 @@ func addUser(username, password, email string) string { http.Handle("/workspace/"+username+"/", 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 } @@ -307,14 +306,14 @@ func addUser(username, password, email string) string { func helloWorld(workspace string) { dir := workspace + conf.PathSeparator + "src" + conf.PathSeparator + "hello" if err := os.MkdirAll(dir, 0755); nil != err { - glog.Error(err) + logger.Error(err) return } fout, err := os.Create(dir + conf.PathSeparator + "main.go") if nil != err { - glog.Error(err) + logger.Error(err) os.Exit(-1) } diff --git a/shell/shells.go b/shell/shells.go index 8042a30..a0a6a98 100644 --- a/shell/shells.go +++ b/shell/shells.go @@ -28,9 +28,9 @@ import ( "github.com/b3log/wide/conf" "github.com/b3log/wide/i18n" + "github.com/b3log/wide/log" "github.com/b3log/wide/session" "github.com/b3log/wide/util" - "github.com/golang/glog" "github.com/gorilla/websocket" ) @@ -39,6 +39,9 @@ import ( // > var ShellWS = map[string]*util.WSChannel{} +// Logger. +var logger = log.NewLogger(os.Stdout) + // IndexHandler handles request of Shell index. func IndexHandler(w http.ResponseWriter, r *http.Request) { httpSession, _ := session.HTTPSession.Get(r, "wide-session") @@ -67,12 +70,12 @@ func IndexHandler(w http.ResponseWriter, r *http.Request) { 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") if nil != err { - glog.Error(err) + logger.Error(err) http.Error(w, err.Error(), 500) return @@ -104,13 +107,13 @@ func WSHandler(w http.ResponseWriter, r *http.Request) { 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{}{} for { if err := wsChan.ReadJSON(&input); err != nil { - glog.Error("Shell WS ERROR: " + err.Error()) + logger.Error("Shell WS ERROR: " + err.Error()) return } @@ -139,7 +142,7 @@ func WSHandler(w http.ResponseWriter, r *http.Request) { ret = map[string]interface{}{"output": output, "cmd": "shell-output"} if err := wsChan.WriteJSON(&ret); err != nil { - glog.Error("Shell WS ERROR: " + err.Error()) + logger.Error("Shell WS ERROR: " + err.Error()) return } diff --git a/util/file.go b/util/file.go index 6330677..13eb510 100644 --- a/util/file.go +++ b/util/file.go @@ -1,11 +1,11 @@ // Copyright (c) 2014, B3log -// +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,9 +18,12 @@ import ( "os" "strings" - "github.com/golang/glog" + "github.com/b3log/wide/log" ) +// Logger. +var fileLogger = log.NewLogger(os.Stdout) + type myfile struct{} // File utilities. @@ -70,7 +73,7 @@ func (*myfile) IsImg(extension string) bool { func (*myfile) IsDir(path string) bool { fio, err := os.Lstat(path) 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 } diff --git a/util/panic.go b/util/panic.go index 4dbf1e9..f7562c5 100644 --- a/util/panic.go +++ b/util/panic.go @@ -15,14 +15,18 @@ package util import ( + "os" "runtime/debug" - "github.com/golang/glog" + "github.com/b3log/wide/log" ) +// Logger. +var logger = log.NewLogger(os.Stdout) + // Recover recovers a panic. func Recover() { 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()) } } diff --git a/util/ret.go b/util/ret.go index 4e74ddb..9936fc6 100644 --- a/util/ret.go +++ b/util/ret.go @@ -18,17 +18,21 @@ import ( "compress/gzip" "encoding/json" "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". func RetJSON(w http.ResponseWriter, r *http.Request, res map[string]interface{}) { w.Header().Set("Content-Type", "application/json") data, err := json.Marshal(res) if err != nil { - glog.Error(err) + retLogger.Error(err) return } @@ -43,13 +47,13 @@ func RetGzJSON(w http.ResponseWriter, r *http.Request, res map[string]interface{ gz := gzip.NewWriter(w) err := json.NewEncoder(gz).Encode(res) if nil != err { - glog.Error(err) + retLogger.Error(err) return } err = gz.Close() if nil != err { - glog.Error(err) + retLogger.Error(err) return }