如何正确地将日志记录器注入到我的代码的数据库层中?

huangapple go评论122阅读模式
英文:

How do I properly inject loggers into the database layer of my code?

问题

我的主要问题是如何将日志记录器注入到与模型相关联的函数中?
例如,如果我们有一个User模型:

  1. type User struct {
  2. id string `json:"id" bson:"id"`
  3. name string `json:"name" bson:"name"`
  4. }

然后,假设我们有一个附加到它的函数:

  1. func (user *User) Save() {
  2. ...
  3. }

现在,我想做的是创建一个结构体,其中包含日志记录器和其他相关信息:

  1. type UserStruct struct {
  2. logger ...
  3. dbConn ...
  4. ...
  5. }

现在我的问题是,如果我将其注入到控制器中,那么它们将可以访问它们不需要的对象。
我找不到一种好的方法来将其与控制器隔离开,并只将模型上的函数注入到控制器中。

英文:

My main problem is how to inject loggers into the functions attached to the models?
So for example, if we have a User model

  1. type User struct {
  2. id string `json:"id" bson:"id"`
  3. name string `json:"name" bson:"name"`
  4. }

and then let's we have a function attached to it

  1. func (user *User) Save() {
  2. ...
  3. }

Now what I want to do with this is to create an struct that has logger and other information attached with it

  1. type UserStruct struct {
  2. logger ...
  3. dbConn ...
  4. ...
  5. }

Now my problem is that if I inject this into the controllers then they would have access to the objects that they don't need.
I can't find a nice way to isolate these from the controller and only inject the functions on the models into the controller.

答案1

得分: 3

我建议在Go中使用一个持久层来接收所有这些数据对象,而不是实现一个活动记录模式。例如:

  1. type Persistence struct {
  2. logger logging.Logger
  3. conn *mongo.Client
  4. // ...
  5. }
  6. func NewPersistence(...) (*Persistence, error) {
  7. // 连接到Mongo等等
  8. return &Persistence{...}, nil
  9. }
  10. func (p *Persistence) SaveUser(user *User) error {
  11. // ...
  12. }
  13. func (p *Persistence) FindUserByName(username string) (*User, error) {
  14. // ...
  15. }

这样做可以将数据对象的持久化逻辑与其他业务逻辑分离,提高代码的可维护性和可测试性。

英文:

Rather than implementing an active record pattern in Go, I'd suggest using a persistence layer that receives all those data objects like User. For example:

  1. type Persistence struct {
  2. logger logging.Logger
  3. conn *mongo.Client
  4. // ...
  5. }
  6. func NewPersistence(...) (*Persistence, error) {
  7. // connect to mongo etc
  8. return &Persistence{...}, nil
  9. }
  10. func (p *Persistence) SaveUser(user *User) error {
  11. // ...
  12. }
  13. func (p *Persistence) FindUserByName(username string) (*User, error) {
  14. // ...
  15. }

huangapple
  • 本文由 发表于 2021年8月25日 19:38:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/68922220.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定