不知道为什么我的go做成windows service服务,log文件就不生成出来了

main.go

package main

import (
    "github.com/robfig/cron"
    "fmt"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
    "reflect"
    "os"
    "os/exec"
    "time"
    "github.com/jander/golog/logger"
    "github.com/kardianos/service"
    "github.com/BurntSushi/toml"
    "strings"
    "log"
)
type TestJob struct {
}

type MongoInfo struct {
    Mongoconnstr   string
    Logpath  string
}

func readMongoStr_toml() string {
    var cg MongoInfo
    var cpath string = "./config.toml"
    if _, err := toml.DecodeFile(cpath, &cg); err != nil {
        fmt.Println(err);
    }

    //fmt.Printf("%v\n", cg.Mongoconnstr)
    return cg.Mongoconnstr
}

func readLogPath_toml() string {
    var cg MongoInfo
    var cpath string = "./config.toml"
    if _, err := toml.DecodeFile(cpath, &cg); err != nil {
        fmt.Println(err);
    }

    //fmt.Printf("%v\n", cg.Mongoconnstr)
    return cg.Logpath
}

func writeLog(message string) {
    //C:\GoProj\src\mongomonitor
    today := time.Now().Format("2006-01-02")
    logPath := readLogPath_toml()
    //path:= "C:\\GoProj\\src\\mongomonitor\\"

    file := strings.Join([]string{ logPath,"", today, ".", "log"},"")
    //file := "./" + time.Now().Format("2006-01-02") + ".log"

    logFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
    if nil != err {
        panic(err)
    }

    loger := log.New(logFile, "前缀", log.Ldate|log.Ltime|log.Lshortfile)

    //Flags返回Logger的输出选项
    fmt.Println(loger.Flags())
    fmt.Println("************")
    //SetFlags设置输出选项
    loger.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)

    //返回输出前缀
    fmt.Println(loger.Prefix())
    //设置输出前缀
    loger.SetPrefix("info_")

    //获取输出项
    fmt.Println(log.Flags())
    //获取前缀
    fmt.Printf(log.Prefix())
    //输出内容
    loger.Output(2, message)
    //格式化输出
    //loger.Fatal(message)
}

func (this TestJob) Run() {
    fmt.Println("Monogo monitor start...")
    var sl []string

    mongoConnStr := readMongoStr_toml()
    fmt.Println(mongoConnStr)
    sl = append(sl,mongoConnStr)

    sess, err := mgo.Dial(mongoConnStr)
    if err != nil {
        fmt.Println(err)
        sl = append(sl,"connect failed")
        fmt.Println("connect failed")

        time.Sleep(60000 * time.Millisecond)

        ww, err := exec.Command("CMD", "/C", " net stop EsSync").Output()
        if err != nil {
            //log.Fatal(err.Error())
            fmt.Println(err.Error())
        }

        sl = append(sl,string(ww))
        fmt.Println(string(ww))
        time.Sleep(8000 * time.Millisecond)

        ww, err = exec.Command("CMD", "/C", " taskkill -f -im node.exe").Output()
        if err != nil {
            //log.Fatal(err.Error())
            fmt.Println(err.Error())
        }
        fmt.Println(string(ww))
        sl = append(sl,string(ww))

        time.Sleep(8000 * time.Millisecond)
        ww, err = exec.Command("CMD", "/C", " net start EsSync").Output()
        if err != nil {
            //log.Fatal(err.Error())
            fmt.Println(err.Error())
        }
        fmt.Println(string(ww))
        sl = append(sl,string(ww))
        message := strings.Join(sl, "")
        writeLog(message)
    }
    defer sess.Close()

    result := bson.M{}
    if err := sess.DB("admin").Run(bson.M{"replSetGetStatus": 1}, &result); err != nil {
        panic(err)
    }
    replicaCoun:= print_json(result,0)
    if(replicaCoun<2){

        time.Sleep(30000 * time.Millisecond)

        ww, err := exec.Command("CMD", "/C", " net stop EsSync").Output()
        if err != nil {
            fmt.Println(err.Error())
            //log.Fatal(err.Error())
        }
        fmt.Println(string(ww))
        sl = append(sl,string(ww))
        time.Sleep(8000 * time.Millisecond)

        ww, err = exec.Command("CMD", "/C", " taskkill -f -im node.exe").Output()
        if err != nil {
            //log.Fatal(err.Error())
            fmt.Println(err.Error())
        }
        fmt.Println(string(ww))
        sl = append(sl,string(ww))
        time.Sleep(8000 * time.Millisecond)

        ww, err = exec.Command("CMD", "/C", " net start EsSync").Output()
        if err != nil {
            //log.Fatal(err.Error())
            fmt.Println(err.Error())
        }
        sl = append(sl,string(ww))
        message := strings.Join(sl, "")
        writeLog(message)
        fmt.Println(string(ww))
    }

    fmt.Println("Monogo monitor end...")
}

func print_jsonold(m map[string]interface{},rpCount int) int {
    replicaCount := 0
    for k, v := range m {
        switch vv := v.(type) {
        case string:
            if(vv=="PRIMARY" || vv=="SECONDARY") {
                replicaCount +=1
            }
            fmt.Println(k, "is string", vv)

        case interface{}:
            switch tt := vv.(type) {
             case string:
                fmt.Println(tt)
             case []interface{}:
                    for i, u := range tt {
                        switch mm := u.(type) {
                        case interface{}:
                        default:
                            fmt.Println(mm, "is of a type I don't know how to handle ", fmt.Sprintf("%T", mm))
                        }
                        fmt.Println(i, u)
                    }
            default:
                fmt.Println(tt, "is of a type I don't know how to handle ", fmt.Sprintf("%T", tt))

            }

            fmt.Println(vv)
        case map[string]interface{}:
            fmt.Println(k, "is an map:")
            print_json(vv,replicaCount)
        default:
            fmt.Println(k, "is of a type I don't know how to handle ", fmt.Sprintf("%T", v))
        }
    }
    return replicaCount
}

func print_json(m map[string]interface{},rpCount int) int {
    replicaCount := 0
    for _, v := range m["members"].([]interface{}) {
        fmt.Println(v)
        switch mm := v.(type) {
        case interface{}:
            v := reflect.ValueOf(mm)
            if v.Kind() == reflect.Map {
                for _, key := range v.MapKeys() {
                    strct := v.MapIndex(key)
                    if(key.Interface()=="stateStr" && (strct.Interface()=="SECONDARY"|| strct.Interface()=="PRIMARY")) {
                        replicaCount +=1
                    }
                }
            }
        default:
            fmt.Println("test")
        }
    }
    return replicaCount
}

func parse_json(m map[string]interface{}) {
    for k, v := range m {
        switch vv := v.(type) {
        case string:
            fmt.Println(k, "is string", vv)
        case float64:
            fmt.Println(k, "is float", int64(vv))
        case int:
            fmt.Println(k, "is int", vv)
        case []interface{}:
            fmt.Println(k, "is an array:")
            for i, u := range vv {
                fmt.Println(i, u)
            }
        case nil:
            fmt.Println(k, "is nil", "null")
        case map[string]interface{}:
            fmt.Println(k, "is an map:")
        default:
            fmt.Println(k, "is of a type I don't know how to handle ", fmt.Sprintf("%T", v))
        }
    }
}

func process(in interface{}) {
    v := reflect.ValueOf(in)
    if v.Kind() == reflect.Map {
        for _, key := range v.MapKeys() {
            strct := v.MapIndex(key)
            fmt.Println(key.Interface(), strct.Interface())
        }
    }
}

type program struct{}

func (p *program) Start(s service.Service) error {
    go p.run()
    return nil
}

func (p *program) run() {
    c := cron.New()
    spec := "0 */3 * * * ?"
    c.AddJob(spec,TestJob{})
    c.Start()

    select{}
}

func (p *program) Stop(s service.Service) error {
    return nil
}

func main() {
    svcConfig := &service.Config{
        Name:        "MongoMonitorForESSync",
        DisplayName: "MongoMonitorForESSync",
        Description: "MongoMonitor for ESDataSync",
    }

    prg := &program{}
    s, err := service.New(prg, svcConfig)
    if err != nil {
        logger.Fatal(err)
    }

    if err != nil {
        logger.Fatal(err)
    }

    if len(os.Args) > 1 {
        if os.Args[1] == "install" {
            s.Install()
            logger.Println("install success")
            return
        }

        if os.Args[1] == "remove" {
            s.Uninstall()
            logger.Println("remove success")
            return
        }
    }

    err = s.Run()
    if err != nil {
        logger.Error(err)
    }
}

config.toml

mongoconnstr="mongodb://Admin:Pass1234@localhost:29031/admin"
logpath="C:\\GoProj\\src\\mongomonitor\\"

在正常运行go run main.go的时候是会生成log文件到mongomonitor目录下的,但是作成windows service就log文件不生成出来了,服务也一直运行着,就是log不生成出来,请高手指点

已邀请:

halfhuman - 80后IT

赞同来自:

权限问题?目录不存在?

swconfidence - golang爱好者

赞同来自:

目录也存在,单独跑go run main.go可以正常生成log在目录下面,一做成服务就log文件生成不出来了

jicg - 杂而不精

赞同来自:

不行,就做成wins系统的任务计划,试试

morya

赞同来自:

听起来像是1楼说的问题:

  1. 权限不对
  2. 目录不合理

做成服务后,是不是cwd变动了,导致相对路径不对,最终写不出。 是不是做成服务后,权限降低了,导致无法打开文件

jicg - 杂而不精

赞同来自:

如果是pwd变动了,你先试下绝对路径是否可以。可以的话,你就需要抓运行时目录 方法:osext.ExecutableFolder()

dir, _ := osext.ExecutableFolder()
    logpath := path.Join(dir, "log.log")
    logconf:=strings.Replace(fmt.Sprintf(`{"filename":"%s","daily":true}`, logpath),"\\","/",-1)

    log.Println(logconf)
    logs.Async()
    if err :=logs.SetLogger(logs.AdapterFile,logconf);err!=nil{
        log.Println( err)
    }

如果是权限问题:https://gocn.vip/question/263 ,试下这个,不行试下就用系统的任务计划

swconfidence - golang爱好者

赞同来自:

@jicg, 试了您说的方法,抓运行时目录,然后配置上运行目录,再次运行go run main.go,就直接报错找不到那个运行时目录,后来又试了https://gocn.vip/question/263 这里面说的方法,也加上了,也build了,生成了nac.syso文件,后来也不起作用,只能再试下系统的任务计划了,谢谢

swconfidence - golang爱好者

赞同来自:

解决了,由于这个路径写的不对导致的 var cpath string = "./config.toml",应该写成绝对路径,然后就可以了,多谢大家的指点,幸好做成了任务计划,跑起来弹出的错误提示说的找不到文件

要回复问题请先登录注册