dongyu9263 2015-03-25 19:03
浏览 341
已采纳

我们可以将所有控制台日志定向到文件吗?

when running web app locally with command

go run MainPackageFile.go

and we can map logger e.g with martini

m := martini.Classic()
m.Get("/m", func() string {
  return "Hello world!"
})
m.Map(log.New(f, "[martini]", log.LstdFlags))

however what if there is something wrong outside the code, e.g Go not able to download package etc... is there a way to get those go runtime log? when running locally errors will print out onto console. is there a way when running in server, we can have all those log write into text file?

  • 写回答

2条回答 默认 最新

  • draxu26480 2015-03-25 19:17
    关注

    You can use this function to redirect standard error to a file. This will receive tracebacks.

    // redirectStderr to the file passed in
    func redirectStderr(f *os.File) {
    err := syscall.Dup2(int(f.Fd()), int(os.Stderr.Fd()))
        if err != nil {
            log.Fatalf("Failed to redirect stderr to file: %v", err)
        }
    }
    

    It only works on linux/mac/unix.

    Here is how to do the same thing for windows

    var (
        kernel32 = syscall.MustLoadDLL("kernel32.dll")
        procSetStdHandle = kernel32.MustFindProc("SetStdHandle")
    )
    
    func setStdHandle(stdhandle int32, handle syscall.Handle) error {
        r0, _, e1 := syscall.Syscall(procSetStdHandle.Addr(), 2, uintptr(stdhandle), uintptr(handle), 0)
        if r0 == 0 {
            if e1 != 0 {
                return error(e1)
            }
            return syscall.EINVAL
        }
        return nil
    }
    
    // redirectStderr to the file passed in
    func redirectStderr(f *os.File) {
        err := setStdHandle(syscall.STD_ERROR_HANDLE, syscall.Handle(f.Fd()))
        if err != nil {
            log.Fatalf("Failed to redirect stderr to file: %v", err)
        }
    }
    

    Original code from minux

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c