duan051347 2018-06-26 19:32
浏览 89
已采纳

去测试删除logger.SetLogging日志文件

I have a TestCase for a function that defines a log file path, then sets logger, so that log.* statements are written to standard out and the log file:

lf, err := os.Create(logFile)
mw := io.MultiWriter(os.Stdout, lf)
log.SetOutput(mw)

In my Test case I'm attempting to cleanup at the end, but it appears there is a lock on the file still, which means the Os.Remove() call is not working (or even returning an error)

I've tried to SetOutput to nil as well as using a defer statement.

func TestSetLogging(t *testing.T) {
// do stuff
...
log.Println("this should be in logger file")

// cleanup
log.SetOutput(nil)
defer os.Remove(logFile)
}

Yet, the logFile still appears on disk. How can I delete this file?

  • 写回答

1条回答 默认 最新

  • douxia6554 2018-06-27 17:10
    关注

    Try calling:

    lf.Close()
    

    before

    os.Remove(logFile)
    

    or you can replace

    defer os.Remove(logFile)
    

    with:

    defer func() {
      lf.Close()
      os.Remove(logFile)
    }()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件