summaryrefslogtreecommitdiffstats
path: root/modules/log/database.go
blob: 5857cb6d66bdfef56b409b23af8a6edf24acc991 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package log

import (
	"encoding/json"

	"github.com/go-xorm/xorm"
)

type Log struct {
	Id    int64
	Level int
	Msg   string `xorm:"TEXT"`
}

// DatabaseWriter implements LoggerInterface and is used to log into database.
type DatabaseWriter struct {
	Driver string `json:"driver"`
	Conn   string `json:"conn"`
	Level  int    `json:"level"`
	x      *xorm.Engine
}

func NewDatabase() LoggerInterface {
	return &DatabaseWriter{Level: TRACE}
}

// init database writer with json config.
// config like:
//	{
//		"driver": "mysql"
//		"conn":"root:root@tcp(127.0.0.1:3306)/gogs?charset=utf8",
//		"level": 0
//	}
// connection string is based on xorm.
func (d *DatabaseWriter) Init(jsonconfig string) (err error) {
	if err = json.Unmarshal([]byte(jsonconfig), d); err != nil {
		return err
	}
	d.x, err = xorm.NewEngine(d.Driver, d.Conn)
	if err != nil {
		return err
	}
	return d.x.Sync(new(Log))
}

// write message in database writer.
func (d *DatabaseWriter) WriteMsg(msg string, skip, level int) error {
	if level < d.Level {
		return nil
	}

	_, err := d.x.Insert(&Log{Level: level, Msg: msg})
	return err
}

func (_ *DatabaseWriter) Flush() {
}

func (_ *DatabaseWriter) Destroy() {
}

func init() {
	Register("database", NewDatabase)
}