正确处理Golang的全球采伐问题 [英] Correct approach to global logging in Golang

查看:103
本文介绍了正确处理Golang的全球采伐问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go的应用程序日志模式是什么?




  • 创建一个单独的<$ c $,如果我有5个goroutines需要登录c> log.Logger 并传递它?

  • 传递指向 log.Logger

  • 每个goroutine或函数是否应该创建一个记录器?

  • 我应该创建记录器作为全局变量吗?

解决方案



  • 创建一个log.Logger并传递它?


这是可能的。 log.Logger 可以在多个goroutine中同时使用。



< blockquote>

  • 传递指向该log.Logger的指针?


log.New 返回一个 *记录器这通常表示您应该将对象作为指针传递。将值作为值传递会创建一个结构的副本(即Logger的副本),然后多个goroutines可能会写入相同的 io .Writer 同时。这可能是一个严重的问题,取决于作者的实现。



  • 每个goroutine或函数应该创建一个记录器?


我不会为每个函数或goroutine创建一个单独的记录器。 Goroutines(和函数)用于非常轻量级的任务,这不会证明维护单独的记录器是合理的。为您的项目的每个更大的组件创建一个记录器可能是一个好主意。例如,如果您的项目使用SMTP服务发送邮件,则为邮件服务创建单独的记录器听起来像是个好主意,这样您就可以单独过滤和关闭输出。



  • 我应该创建记录器作为全局变量吗?

这取决于你的包裹。在以前的邮件服务示例中,最好为每个服务实例都设置一个记录器,以便用户在使用gmail邮件服务时记录失败的方式与使用本地MTA时发生的失败不同(例如sendmail )。


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?

解决方案

  • 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).

这篇关于正确处理Golang的全球采伐问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆