本文介绍了转到:创建io.Writer接口以登录到mongodb数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用go(golang):

Using go (golang):

有没有一种方法可以创建输出到数据库的记录器?

Is there a way to create a logger that outputs to a database?

或更准确地说,我可以实现某种io.Writer接口,并将其作为log.New()的第一个参数传递吗?

Or more precisely, can I implement some kind of io.Writer interface that I can pass as the first argument to log.New()?

EG:(dbLogger将接收日志的输出并将其写入数据库)

EG: (dbLogger would receive the output of the log and write it to the database)

logger := log.New(dbLogger, "dbLog: ", log.Lshortfile)logger.Print("This message will be stored in the database")

logger := log.New(dbLogger, "dbLog: ", log.Lshortfile)logger.Print("This message will be stored in the database")

我认为我应该只创建自己的数据库日志记录功能,但是我很想知道是否已经可以使用该语言的现有工具来做到这一点.

I would assume that I should just create my own database logging function, but I was curious to see if there is already a way of doing this using the existing tools in the language.

在某些情况下,我使用 mgo.v2 处理我的mongodb数据库,但除了 GridFS ,我认为这可以解决另一个问题.

For some context, I'm using mgo.v2 to handle my mongodb database, but I don't see any io.Writer interfaces there other than in GridFS, which I think solves a different problem.

我仍然对这种语言有所了解,因此我可能在上面不正确地使用了一些术语.任何更正都非常欢迎.

I'm also still getting my head around the language, so I may have used some terms above incorrecly. Any corrections are very welcome.

推荐答案

这很容易实现,因为 log.Logger 类型保证将每个日志消息传递到目标 io.Writer 和一个Writer.Write()调用:

This is easily doable, because the log.Logger type guarantees that each log message is delivered to the destination io.Writer with a single Writer.Write() call:

因此,基本上,您只需要创建一个实现io.Writer的类型,该类型的Write()方法将使用字节片的内容创建一个新文档,并将其保存在MongoDB中.

So basically you just need to create a type which implements io.Writer, and whose Write() method creates a new document with the contents of the byte slice, and saves it in the MongoDB.

这是一个简单的实现,可以实现:

Here's a simple implementation which does that:

type MongoWriter struct {
    sess *mgo.Session
}

func (mw *MongoWriter) Write(p []byte) (n int, err error) {
    c := mw.sess.DB("").C("log")
    err = c.Insert(bson.M{
        "created": time.Now(),
        "msg":     string(p),
    })
    if err != nil {
        return
    }
    return len(p), nil
}

使用它:

sess := ... // Get a MongoDB session

mw := &MongoWriter{sess}
log.SetOutput(mw)

// Now the default Logger of the log package uses our MongoWriter.
// Generate a log message that will be inserted into MongoDB:
log.Println("I'm the first log message.")
log.Println("I'm multi-line,\nbut will still be in a single log message.")

很明显,如果您使用的是另一个log.Logger实例,请将MongoWriter设置为该实例,例如:

Obviously if you're using another log.Logger instance, set the MongoWriter to that, e.g.:

mylogger := log.New(mw, "", 0)
mylogger.Println("Custom logger")

请注意,日志消息以换行符结尾,因为log.Logger追加了日志,即使日志消息本身不以换行符结尾.如果您不想记录结尾的换行符,则可以简单地将其剪切掉,例如:

Note that the log messages end with newline as log.Logger appends it even if the log message itself does not end with newline. If you don't want to log the ending newline, you may simply cut it, e.g.:

func (mw *MongoWriter) Write(p []byte) (n int, err error) {
    origLen := len(p)
    if len(p) > 0 && p[len(p)-1] == '\n' {
        p = p[:len(p)-1] // Cut terminating newline
    }

    c := mw.sess.DB("").C("log")

    // ... the rest is the same

    return origLen, nil // Must return original length (we resliced p)
}

这篇关于转到:创建io.Writer接口以登录到mongodb数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 10:35