log.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package models
  2. import (
  3. "encoding/json"
  4. "strconv"
  5. "time"
  6. "github.com/astaxie/beego"
  7. "github.com/astaxie/beego/orm"
  8. )
  9. type UserLog struct {
  10. Id int
  11. Name string `orm:"index"`
  12. Time int64
  13. Operate string
  14. Data string `orm:type(text)`
  15. }
  16. func init() {
  17. orm.RegisterModel(new(UserLog))
  18. }
  19. func (c *UserLog) TableName() string {
  20. return "tb_log"
  21. }
  22. func SaveLog(name string, operate string, v interface{}) (int64, error) {
  23. buff, _ := json.Marshal(v)
  24. l := &UserLog{
  25. Name: name,
  26. Operate: operate,
  27. Time: time.Now().Unix(),
  28. Data: string(buff),
  29. }
  30. o := orm.NewOrm()
  31. return o.Insert(l)
  32. }
  33. func QueryLog(name string, begin_ts int64, end_ts int64, operate string, count int) []*UserLog {
  34. var logs []*UserLog
  35. sql := "SELECT * from tb_log"
  36. where := ""
  37. if name != "" {
  38. if where == "" {
  39. where = " name = '" + name + "'"
  40. } else {
  41. where += " and name = '" + name + "'"
  42. }
  43. }
  44. if begin_ts != 0 {
  45. if where == "" {
  46. where = " time >= " + strconv.Itoa(int(begin_ts))
  47. } else {
  48. where += " and time >= " + strconv.Itoa(int(begin_ts))
  49. }
  50. }
  51. if end_ts != 0 {
  52. if where == "" {
  53. where = " time <= " + strconv.Itoa(int(end_ts))
  54. } else {
  55. where += " and time <= " + strconv.Itoa(int(end_ts))
  56. }
  57. }
  58. if operate != "" {
  59. if where == "" {
  60. where = " operate = '" + operate + "'"
  61. } else {
  62. where += " and operate = '" + operate + "'"
  63. }
  64. }
  65. if where != "" {
  66. sql += " where " + where
  67. }
  68. sql += " order by time desc"
  69. if count > 0 {
  70. sql += " limit " + strconv.Itoa(count)
  71. }
  72. o := orm.NewOrm()
  73. _, err := o.Raw(sql).QueryRows(&logs)
  74. if err != nil {
  75. beego.Info(sql)
  76. beego.Warn("query log error, info: ", err.Error())
  77. }
  78. return logs
  79. }