MySQL Hook for Logrus
A mysql-based logrus hook
$ go get -u -v github.com/LyricTian/logrus-mysql-hook
import "github.com/LyricTian/logrus-mysql-hook"
// ...
mysqlHook := mysqlhook.Default(db,"log")
defer mysqlHook.Flush()
log := logrus.New()
log.AddHook(mysqlHook)
package main
import (
"database/sql"
"fmt"
"github.com/LyricTian/logrus-mysql-hook"
"github.com/Sirupsen/logrus"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
tableName := "e_log"
mysqlHook := mysqlhook.Default(db, tableName)
defer db.Exec(fmt.Sprintf("drop table %s", tableName))
log := logrus.New()
log.AddHook(mysqlHook)
log.WithField("foo", "bar").Info("foo test")
mysqlHook.Flush()
var message string
row := db.QueryRow(fmt.Sprintf("select message from %s", tableName))
err = row.Scan(&message)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(message)
// Output: foo test
}
Copyright (c) 2018 Lyric