重构 log

This commit is contained in:
dengsgo 2020-01-02 17:25:02 +08:00
parent 00e34193aa
commit 3351429515
5 changed files with 61 additions and 57 deletions

View File

@ -14,15 +14,15 @@ func getPidFile() string {
func runAsDeamon() (int, error) {
if runtime.GOOS == "windows" {
logAndExit(PreError, "daemons mode cannot run on windows.")
logAndExit("daemons mode cannot run on windows.")
}
err := stopDeamon()
if err != nil {
logAndExit(PreError, err)
logAndExit(err)
}
_, err = exec.LookPath("fileboy")
if err != nil {
logAndExit(PreError, "cannot found `fileboy` command in the PATH")
logAndExit("cannot found `fileboy` command in the PATH")
}
deamon := exec.Command("fileboy")
deamon.Dir = projectFolder
@ -30,7 +30,7 @@ func runAsDeamon() (int, error) {
deamon.Stdout = os.Stdout
err = deamon.Start()
if err != nil {
logAndExit(PreError, err)
logAndExit(err)
}
pid := deamon.Process.Pid
if pid != 0 {

View File

@ -18,9 +18,6 @@ import (
const (
Version = 1
PreError = "ERROR:"
PreWarn = "Warn:"
InstExecWhenStart = "exec-when-start"
InstShouldFinish = "should-finish"
)
@ -56,16 +53,16 @@ func parseConfig() {
cfg = new(FileGirl)
fc, err := ioutil.ReadFile(getFileGirlPath())
if err != nil {
log.Println(PreError, "The filegirl.yaml file in", projectFolder, "is not exist! ", err)
logError("The filegirl.yaml file in", projectFolder, "is not exist! ", err)
fmt.Print(firstRunHelp)
logAndExit("Fileboy unable to run.")
}
err = yaml.Unmarshal(fc, cfg)
if err != nil {
logAndExit(PreError, "Parsed filegirl.yaml failed: ", err)
logAndExit("Parsed filegirl.yaml failed: ", err)
}
if cfg.Core.Version > Version {
logAndExit(PreError, "Current fileboy support max version : ", Version)
logAndExit("Current fileboy support max version : ", Version)
}
// init map
cfg.Monitor.TypesMap = map[string]bool{}
@ -108,15 +105,15 @@ func eventDispatcher(event fsnotify.Event) {
}
func addWatcher() {
log.Println("collecting directory information...")
logInfo("collecting directory information...")
dirsMap := map[string]bool{}
for _, dir := range cfg.Monitor.IncludeDirs {
darr := dirParse2Array(dir)
if len(darr) < 1 || len(darr) > 2 {
logAndExit(PreError, "filegirl section monitor dirs is error. ", dir)
logAndExit("filegirl section monitor dirs is error. ", dir)
}
if strings.HasPrefix(darr[0], "/") {
logAndExit(PreError, "dirs must be relative paths ! err path:", dir)
logAndExit("dirs must be relative paths ! err path:", dir)
}
if darr[0] == "." {
if len(darr) == 2 && darr[1] == "*" {
@ -146,7 +143,7 @@ func addWatcher() {
}
for _, dir := range cfg.Monitor.ExceptDirs {
if dir == "." {
logAndExit(PreError, "exceptDirs must is not project root path ! err path:", dir)
logAndExit("exceptDirs must is not project root path ! err path:", dir)
}
p := projectFolder + "/" + dir
delete(dirsMap, p)
@ -155,14 +152,14 @@ func addWatcher() {
})
}
for dir := range dirsMap {
log.Println("watcher add -> ", dir)
logInfo("watcher add -> ", dir)
err := watcher.Add(dir)
if err != nil {
logAndExit(PreError, err)
logAndExit(err)
}
}
log.Println("total monitored dirs: " + strconv.Itoa(len(dirsMap)))
log.Println("fileboy is ready.")
logInfo("total monitored dirs: " + strconv.Itoa(len(dirsMap)))
logInfo("fileboy is ready.")
cfg.Monitor.DirsMap = dirsMap
}
@ -191,7 +188,7 @@ func initWatcher() {
if !ok {
return
}
log.Println(PreError, err)
logError(err)
}
}
}()
@ -226,9 +223,9 @@ func watchChangeHandler(event fsnotify.Event) {
err := watcher.Add(event.Name)
if err == nil {
do = true
log.Println("watcher add -> ", event.Name)
logInfo("watcher add -> ", event.Name)
} else {
log.Println(PreWarn, "watcher add faild:", event.Name, err)
logWarn("watcher add faild:", event.Name, err)
}
}
@ -241,9 +238,9 @@ func watchChangeHandler(event fsnotify.Event) {
_ = watcher.Remove(event.Name)
err := watcher.Add(event.Name)
if err == nil {
log.Println("watcher add -> ", event.Name)
logInfo("watcher add -> ", event.Name)
} else {
log.Println(PreWarn, "watcher add faild:", event.Name, err)
logWarn("watcher add faild:", event.Name, err)
}
}
}
@ -267,30 +264,30 @@ func parseArgs() {
case "deamon":
pid, err := runAsDeamon()
if err != nil {
logAndExit(PreError, err)
logAndExit(err)
}
log.Println("PID:", pid)
log.Println("fileboy is ready. the main process will run as a daemons")
logInfo("PID:", pid)
logInfo("fileboy is ready. the main process will run as a daemons")
return
case "stop":
err := stopDeamon()
if err != nil {
logAndExit(PreError, err)
logAndExit(err)
}
log.Println("fileboy daemon is stoped.")
logInfo("fileboy daemon is stoped.")
return
case "init":
_, err := ioutil.ReadFile(getFileGirlPath())
if err == nil {
log.Println(PreError, "Profile filegirl.yaml already exists.")
logError("Profile filegirl.yaml already exists.")
logAndExit("If you want to regenerate filegirl.yaml, delete it first")
}
err = ioutil.WriteFile(getFileGirlPath(), []byte(exampleFileGirl), 0644)
if err != nil {
log.Println(PreError, "Profile filegirl.yaml create failed! ", err)
logError("Profile filegirl.yaml create failed! ", err)
return
}
log.Println("Profile filegirl.yaml created ok")
logInfo("Profile filegirl.yaml created ok")
return
case "exec":
parseConfig()
@ -301,7 +298,7 @@ func parseArgs() {
case "help", "--help", "--h", "-h":
fmt.Print(helpStr)
default:
fmt.Println(PreError, "Unknown parameter, use 'fileboy help' to view available commands")
logAndExit("Unknown parameter, use 'fileboy help' to view available commands")
}
return
default:

View File

@ -3,7 +3,6 @@ package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
"strings"
"time"
@ -35,7 +34,7 @@ func newNetNotifier(callUrl string) *NetNotifier {
func (n *NetNotifier) Put(cf *changedFile) {
if !n.CanPost {
log.Println(PreWarn, "notifier call url ignore. ", n.CallUrl)
logWarn("notifier call url ignore. ", n.CallUrl)
return
}
n.dispatch(&postParams{
@ -50,7 +49,7 @@ func (n *NetNotifier) Put(cf *changedFile) {
func (n *NetNotifier) dispatch(params *postParams) {
b, err := json.Marshal(params)
if err != nil {
log.Println(PreError, "json.Marshal n.params. ", err)
logError("json.Marshal n.params. ", err)
return
}
client := &http.Client{
@ -58,14 +57,14 @@ func (n *NetNotifier) dispatch(params *postParams) {
}
req, err := http.NewRequest("POST", n.CallUrl, bytes.NewBuffer(b))
if err != nil {
log.Println(PreError, "http.NewRequest. ", err)
logError("http.NewRequest. ", err)
return
}
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
req.Header.Set("User-Agent", "FileBoy Net Notifier v1.12")
resp, err := client.Do(req)
if err != nil {
log.Println(PreError, "notifier call failed. err:", err)
logError("notifier call failed. err:", err)
return
}
defer func() {
@ -76,5 +75,5 @@ func (n *NetNotifier) dispatch(params *postParams) {
if resp.StatusCode >= 300 {
// todo retry???
}
log.Println("notifier done .")
logInfo("notifier done .")
}

View File

@ -1,7 +1,6 @@
package main
import (
"log"
"os"
"os/exec"
"sync"
@ -34,7 +33,7 @@ func newTaskMan(delay int, callUrl string) *TaskMan {
if len(t.waitQueue) > 0 {
cf := t.waitQueue[len(t.waitQueue)-1]
if len(t.waitQueue) > 1 {
log.Println("Number of redundant tasks dropped:", len(t.waitQueue)-1)
logInfo("Number of redundant tasks dropped:", len(t.waitQueue)-1)
}
t.waitQueue = []*changedFile{}
go t.preRun(cf)
@ -65,8 +64,8 @@ func (t *TaskMan) Put(cf *changedFile) {
t.waitChan <- true
return
}
log.Println("Waitting for the last task to finish")
log.Println("Number of waiting tasks:", len(t.waitQueue))
logInfo("Waitting for the last task to finish")
logInfo("Number of waiting tasks:", len(t.waitQueue))
} else {
t.preRun(cf)
}
@ -76,27 +75,20 @@ func (t *TaskMan) Put(cf *changedFile) {
func (t *TaskMan) preRun(cf *changedFile) {
if t.cmd != nil && t.cmd.Process != nil {
if err := t.cmd.Process.Kill(); err != nil {
log.Println("stop old process ")
log.Println(PreWarn, "stopped err, reason:", err)
logInfo("stop old process ")
logWarn("stopped err, reason:", err)
}
}
go t.run(cf)
go t.notifier.Put(cf)
}
func (t *TaskMan) waitFinish() {
log.Println("prostate", t.cmd.Process.Pid)
if t.cmd.ProcessState != nil && !t.cmd.ProcessState.Exited() {
}
}
func (t *TaskMan) run(cf *changedFile) {
t.runLock.Lock()
defer t.runLock.Unlock()
for i := 0; i < len(cfg.Command.Exec); i++ {
carr := cmdParse2Array(cfg.Command.Exec[i], cf)
log.Println("EXEC", carr)
logInfo("EXEC", carr)
t.cmd = exec.Command(carr[0], carr[1:]...)
//cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: syscall.CREATE_UNICODE_ENVIRONMENT}
t.cmd.Stdin = os.Stdin
@ -106,19 +98,19 @@ func (t *TaskMan) run(cf *changedFile) {
t.cmd.Env = os.Environ()
err := t.cmd.Start()
if err != nil {
log.Println(PreError, "run command", carr, "error. ", err)
logError("run command", carr, "error. ", err)
break
}
err = t.cmd.Wait()
if err != nil {
log.Println(PreWarn, "command exec failed:", carr, err)
logWarn("command exec failed:", carr, err)
break
}
if t.cmd.Process != nil {
err := t.cmd.Process.Kill()
log.Println(t.cmd.ProcessState)
logInfo(t.cmd.ProcessState)
if t.cmd.ProcessState != nil && !t.cmd.ProcessState.Exited() {
log.Println(PreError, "command cannot stop!", carr, err)
logError("command cannot stop!", carr, err)
}
}
}
@ -126,5 +118,5 @@ func (t *TaskMan) run(cf *changedFile) {
t.cmd = nil
t.waitChan <- true
}
log.Println("EXEC end")
logInfo("EXEC end")
}

16
util.go
View File

@ -81,7 +81,23 @@ func inStrArray(s string, arr []string) bool {
return false
}
func logInfo(v ...interface{}) {
v = append([]interface{}{"I:"}, v...)
log.Println(v...)
}
func logWarn(v ...interface{}) {
v = append([]interface{}{"W:"}, v...)
log.Println(v...)
}
func logError(v ...interface{}) {
v = append([]interface{}{"E:"}, v...)
log.Println(v...)
}
func logAndExit(v ...interface{}) {
v = append([]interface{}{"O:"}, v...)
log.Println(v...)
os.Exit(15)
}