douan6931 2013-08-21 15:35
浏览 785
已采纳

正确的Golang全局日志记录方法

What's the pattern for application logging in Go? If I've got, say, 5 goroutines I need to log from, should I...

  • Create a single log.Logger and pass it around?
  • Pass around a pointer to that log.Logger?
  • Should each goroutine or function create a logger?
  • Should I create the logger as a global variable?
  • 写回答

6条回答 默认 最新

  • dongshao1021 2013-08-21 16:31
    关注
    • Create a single log.Logger and pass it around?

    That is possible. A log.Logger can be used concurrently from multiple goroutines.

    • Pass around a pointer to that log.Logger?

    log.New returns a *Logger which is usually an indication that you should pass the object around as a pointer. Passing it as value would create a copy of the struct (i.e. a copy of the Logger) and then multiple goroutines might write to the same io.Writer concurrently. That might be a serious problem, depending on the implementation of the writer.

    • Should each goroutine or function create a logger?

    I wouldn't create a separate logger for each function or goroutine. Goroutines (and functions) are used for very lightweight tasks that will not justify the maintenance of a separate logger. It's probably a good idea to create a logger for each bigger component of your project. For example, if your project uses a SMTP service for sending mails, creating a separate logger for the mail service sounds like a good idea so that you can filter and turn off the output separately.

    • Should I create the logger as a global variable?

    That depends on your package. In the previous mail service example, it would be probably a good idea to have one logger for each instance of your service, so that users can log failures while using the gmail mail service differently than failures that occured while using the local MTA (e.g. sendmail).

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

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)