drcrc28428 2018-12-10 15:21
浏览 58
已采纳

通过Golang记录器写日志

I am trying to write log by using log.Logger, my code is like bellow. I don't understand why my log can be written using Error inside initLog function but in main function it can't be written to the log file.
Can anybody explain for me?
Thanks.

package main

import (
    "log"
    "net/http"
    "os"
)

const (
    PORT = ":8081"
)

var (
    Error *log.Logger
)

func initLog() {
    errorFile, err := os.OpenFile("error.log", os.O_RDWR|os.O_APPEND, 0660)
    defer errorFile.Close()

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

    Error = log.New(errorFile, "ERROR: ", log.Ldate|log.Ltime)
    Error.SetOutput(errorFile)
    Error.Println("Log error will be written into error.log")

}

func main() {
    initLog()
    Error.Println("Test write log")
    http.ListenAndServe(PORT, http.FileServer(http.Dir('.')))
}
  • 写回答

2条回答 默认 最新

  • dongxie2749 2018-12-10 15:29
    关注

    You're closing the file when returning from initLog() using defer errorFile.Close() so inside main() the file errorFile is closed.

    So comment this line:

    defer errorFile.Close()
    

    And move it to the main().

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里