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

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

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

问题

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

type User struct {
 id string `json:"id" bson:"id"`
 name string `json:"name" bson:"name"`
}

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

func (user *User) Save() {
 ...
}

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

type UserStruct struct {
 logger ...
 dbConn ...
 ...
}

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

英文:

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

type User struct {
 id string `json:"id" bson:"id"`
 name string `json:"name" bson:"name"`
}

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

func (user *User) Save() {
 ...
}

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

type UserStruct struct {
 logger ...
 dbConn ...
 ...
}

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中使用一个持久层来接收所有这些数据对象,而不是实现一个活动记录模式。例如:

type Persistence struct {
    logger logging.Logger
    conn   *mongo.Client
    // ...
}

func NewPersistence(...) (*Persistence, error) {
    // 连接到Mongo等等
    return &Persistence{...}, nil
}

func (p *Persistence) SaveUser(user *User) error {
    // ...
}

func (p *Persistence) FindUserByName(username string) (*User, error) {
    // ...
}

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

英文:

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:

type Persistence struct {
    logger logging.Logger
    conn   *mongo.Client
    // ...
}

func NewPersistence(...) (*Persistence, error) {
    // connect to mongo etc
    return &Persistence{...}, nil
}

func (p *Persistence) SaveUser(user *User) error {
    // ...
}

func (p *Persistence) FindUserByName(username string) (*User, error) {
    // ...
}

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:

确定