全局日志记录的正确方法 [英] Correct approach to global logging

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

问题描述

Go 中应用程序登录的模式是什么?如果我有,比如说,我需要从 5 个 goroutines 登录,我应该...

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

  • 创建一个 log.Logger 并传递它?
  • 传递一个指向那个 log.Logger 的指针?
  • 每个 goroutine 或函数都应该创建一个记录器吗?
  • 我应该将记录器创建为全局变量吗?
  • 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?

推荐答案

  • 创建单个 log.Logger 并将其传递?

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

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

  • 传递指向该日志的指针.Logger?

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

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.

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

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

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.

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

这取决于您的包裹.在前面的邮件服务示例中,为您的服务的每个实例设置一个记录器可能是个好主意,这样用户可以在使用 gmail 邮件服务时记录故障,而不是使用本地 MTA(例如 sendmail).

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

这篇关于全局日志记录的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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