database.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package log
  5. import (
  6. "encoding/json"
  7. "github.com/go-xorm/xorm"
  8. )
  9. type Log struct {
  10. Id int64
  11. Level int
  12. Msg string `xorm:"TEXT"`
  13. }
  14. // DatabaseWriter implements LoggerInterface and is used to log into database.
  15. type DatabaseWriter struct {
  16. Driver string `json:"driver"`
  17. Conn string `json:"conn"`
  18. Level int `json:"level"`
  19. x *xorm.Engine
  20. }
  21. func NewDatabase() LoggerInterface {
  22. return &DatabaseWriter{Level: TRACE}
  23. }
  24. // init database writer with json config.
  25. // config like:
  26. // {
  27. // "driver": "mysql"
  28. // "conn":"root:root@tcp(127.0.0.1:3306)/gogs?charset=utf8",
  29. // "level": 0
  30. // }
  31. // connection string is based on xorm.
  32. func (d *DatabaseWriter) Init(jsonconfig string) (err error) {
  33. if err = json.Unmarshal([]byte(jsonconfig), d); err != nil {
  34. return err
  35. }
  36. d.x, err = xorm.NewEngine(d.Driver, d.Conn)
  37. if err != nil {
  38. return err
  39. }
  40. return d.x.Sync(new(Log))
  41. }
  42. // write message in database writer.
  43. func (d *DatabaseWriter) WriteMsg(msg string, skip, level int) error {
  44. if level < d.Level {
  45. return nil
  46. }
  47. _, err := d.x.Insert(&Log{Level: level, Msg: msg})
  48. return err
  49. }
  50. func (_ *DatabaseWriter) Flush() {
  51. }
  52. func (_ *DatabaseWriter) Destroy() {
  53. }
  54. func init() {
  55. Register("database", NewDatabase)
  56. }