1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('./LogStore');
|
7 |
|
8 | module.exports = class DatabaseLogStore extends Base {
|
9 |
|
10 | constructor (config) {
|
11 | super({
|
12 | table: 'log',
|
13 | key: '_id',
|
14 | observePeriod: 60,
|
15 | maxRows: 10000,
|
16 | ...config
|
17 | });
|
18 | this.db = this.module.getDb(this.db);
|
19 | }
|
20 |
|
21 | init () {
|
22 | if (this.observePeriod) {
|
23 | this.observe();
|
24 | }
|
25 | }
|
26 |
|
27 | save (type, message, data) {
|
28 | this.find().insert(this.format(type, message, data)).catch(err => {
|
29 | console.error(this.wrapClassMessage('save'), err);
|
30 | });
|
31 | }
|
32 |
|
33 | format (type, message, data) {
|
34 | if (message instanceof Exception) {
|
35 | message = message.toString();
|
36 | } else if (message instanceof Error) {
|
37 | message = `${message.message} ${message.stack}`;
|
38 | }
|
39 | return {
|
40 | type,
|
41 | message,
|
42 | data,
|
43 | createdAt: new Date
|
44 | };
|
45 | }
|
46 |
|
47 | observe () {
|
48 | setTimeout(async ()=> {
|
49 | await this.checkout();
|
50 | this.observe();
|
51 | }, this.observePeriod * 1000);
|
52 | }
|
53 |
|
54 | async checkout () {
|
55 | try {
|
56 | await this.truncate();
|
57 | } catch (err) {
|
58 | this.log('error', this.wrapClassMessage('checkout'), err);
|
59 | }
|
60 | }
|
61 |
|
62 | async truncate () {
|
63 | const counter = await this.find().count();
|
64 | if (counter >= this.maxRows + this.maxRows / 2) {
|
65 | const id = await this.find().offset(this.maxRows).order({[this.key]: -1}).scalar(this.key);
|
66 | await this.find().and(['<', this.key, id]).delete();
|
67 | }
|
68 | }
|
69 |
|
70 | find () {
|
71 | return (new Query).db(this.db).from(this.table);
|
72 | }
|
73 | };
|
74 |
|
75 | const Exception = require('../error/Exception');
|
76 | const Query = require('../db/Query'); |
\ | No newline at end of file |