Skip to content

LyricTian/logrus-mysql-hook

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

An asynchronous MySQL Hook for Logrus

Build Codecov ReportCard GoDoc License

Quick Start

Download and install

$ go get -u -v github.com/LyricTian/logrus-mysql-hook

Usage

import "github.com/LyricTian/logrus-mysql-hook"

// ...

mysqlHook := mysqlhook.Default(db,"log")

defer mysqlHook.Flush()

log := logrus.New()
log.AddHook(mysqlHook)

Examples

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 := "t_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
}

Use Extra Item Examples

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 := "t_log"
	extraItems := []*mysqlhook.ExecExtraItem{
		mysqlhook.NewExecExtraItem("type", "varchar(50)"),
		mysqlhook.NewExecExtraItem("user_id", "varchar(50)"),
	}
	mysqlHook := mysqlhook.DefaultWithExtra(db, tableName, extraItems)

	defer db.Exec(fmt.Sprintf("drop table %s", tableName))

	log := logrus.New()
	log.AddHook(mysqlHook)
	log.WithField("foo", "bar").
		WithField("type", "system").
		WithField("user_id", "admin").
		Info("foo test")

	mysqlHook.Flush()

	var (
		message string
		typ     string
		userID  string
	)
	row := db.QueryRow(fmt.Sprintf("select message,type,user_id from %s", tableName))
	err = row.Scan(&message, &typ, &userID)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("[%s-%s]:%s\n", typ, userID, message)

	// Output: [system-admin]:foo test
}

MIT License

Copyright (c) 2018 Lyric