aboutsummaryrefslogtreecommitdiff
path: root/contexts/data/lib/closure-library/closure/goog/gears/logstore.js
blob: 48f8e8f6db63ef4915a190e64d96e9541b7ddbe1 (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview This file implements a store for goog.debug.Logger data.
 */

goog.provide('goog.gears.LogStore');
goog.provide('goog.gears.LogStore.Query');

goog.require('goog.async.Delay');
goog.require('goog.debug.LogManager');
goog.require('goog.debug.LogRecord');
goog.require('goog.debug.Logger');
goog.require('goog.debug.Logger.Level');
goog.require('goog.gears.BaseStore');
goog.require('goog.gears.BaseStore.SchemaType');
goog.require('goog.json');



/**
 * Implements a store for goog.debug.Logger data.
 * @param {goog.gears.Database} database Database.
 * @param {?string=} opt_tableName Name of logging table to use.
 * @extends {goog.gears.BaseStore}
 * @constructor
 */
goog.gears.LogStore = function(database, opt_tableName) {
  goog.gears.BaseStore.call(this, database);

  /**
   * Name of log table.
   * @type {string}
   */
  var tableName = opt_tableName || goog.gears.LogStore.DEFAULT_TABLE_NAME_;
  this.tableName_ = tableName;

  // Override BaseStore schema attribute.
  this.schema = [
    {
      type: goog.gears.BaseStore.SchemaType.TABLE,
      name: tableName,
      columns: [
        // Unique ID.
        'id INTEGER PRIMARY KEY AUTOINCREMENT',
        // Timestamp.
        'millis BIGINT',
        // #goog.debug.Logger.Level value.
        'level INTEGER',
        // Message.
        'msg TEXT',
        // Name of logger object.
        'logger TEXT',
        // Serialized error object.
        'exception TEXT',
        // Full exception text.
        'exceptionText TEXT'
      ]
    },
    {
      type: goog.gears.BaseStore.SchemaType.INDEX,
      name: tableName + 'MillisIndex',
      isUnique: false,
      tableName: tableName,
      columns: ['millis']
    },
    {
      type: goog.gears.BaseStore.SchemaType.INDEX,
      name: tableName + 'LevelIndex',
      isUnique: false,
      tableName: tableName,
      columns: ['level']
    }
  ];

  /**
   * Buffered log records not yet flushed to DB.
   * @type {Array.<goog.debug.LogRecord>}
   * @private
   */
  this.records_ = [];

  /**
   * Save the publish handler so it can be removed.
   * @type {Function}
   * @private
   */
  this.publishHandler_ = goog.bind(this.addLogRecord, this);
};
goog.inherits(goog.gears.LogStore, goog.gears.BaseStore);


/** @override */
goog.gears.LogStore.prototype.version = 1;


/**
 * Whether we are currently capturing logger output.
 * @type {boolean}
 * @private
 */
goog.gears.LogStore.prototype.isCapturing_ = false;


/**
 * Size of buffered log data messages.
 * @type {number}
 * @private
 */
goog.gears.LogStore.prototype.bufferSize_ = 0;


/**
 * Scheduler for pruning action.
 * @type {goog.async.Delay?}
 * @private
 */
goog.gears.LogStore.prototype.delay_ = null;


/**
 * Use this to protect against recursive flushing.
 * @type {boolean}
 * @private
 */
goog.gears.LogStore.prototype.isFlushing_ = false;


/**
 * Logger.
 * @type {goog.debug.Logger}
 * @private
 */
goog.gears.LogStore.prototype.logger_ =
    goog.debug.Logger.getLogger('goog.gears.LogStore');


/**
  * Default value for how many records we keep when pruning.
  * @type {number}
  * @private
  */
goog.gears.LogStore.DEFAULT_PRUNE_KEEPER_COUNT_ = 1000;


/**
  * Default value for how often to auto-prune (10 minutes).
  * @type {number}
  * @private
  */
goog.gears.LogStore.DEFAULT_AUTOPRUNE_INTERVAL_MILLIS_ = 10 * 60 * 1000;


/**
  * The name for the log table.
  * @type {string}
  * @private
  */
goog.gears.LogStore.DEFAULT_TABLE_NAME_ = 'GoogGearsDebugLogStore';


/**
  * Max message bytes to buffer before flushing to database.
  * @type {number}
  * @private
  */
goog.gears.LogStore.MAX_BUFFER_BYTES_ = 200000;


/**
 * Flush buffered log records.
 */
goog.gears.LogStore.prototype.flush = function() {
  if (this.isFlushing_ || !this.getDatabaseInternal()) {
    return;
  }
  this.isFlushing_ = true;

  // Grab local copy of records so database can log during this process.
  this.logger_.info('flushing ' + this.records_.length + ' records');
  var records = this.records_;
  this.records_ = [];

  for (var i = 0; i < records.length; i++) {
    var record = records[i];
    var exception = record.getException();
    var serializedException = exception ? goog.json.serialize(exception) : '';
    var statement = 'INSERT INTO ' + this.tableName_ +
        ' (millis, level, msg, logger, exception, exceptionText)' +
        ' VALUES (?, ?, ?, ?, ?, ?)';
    this.getDatabaseInternal().execute(statement,
        record.getMillis(), record.getLevel().value, record.getMessage(),
        record.getLoggerName(), serializedException,
        record.getExceptionText() || '');
  }

  this.isFlushing_ = false;
};


/**
 * Create new delay object for auto-pruning. Does not stop or
 * start auto-pruning, call #startAutoPrune and #startAutoPrune for that.
 * @param {?number=} opt_count Number of records of recent hitory to keep.
 * @param {?number=} opt_interval Milliseconds to wait before next pruning.
 */
goog.gears.LogStore.prototype.createAutoPruneDelay = function(
    opt_count, opt_interval) {
  if (this.delay_) {
    this.delay_.dispose();
    this.delay_ = null;
  }
  var interval = typeof opt_interval == 'number' ?
      opt_interval : goog.gears.LogStore.DEFAULT_AUTOPRUNE_INTERVAL_MILLIS_;
  var listener = goog.bind(this.autoPrune_, this, opt_count);
  this.delay_ = new goog.async.Delay(listener, interval);
};


/**
 * Enable periodic pruning. As a side effect, this also flushes the memory
 * buffer.
 */
goog.gears.LogStore.prototype.startAutoPrune = function() {
  if (!this.delay_) {
    this.createAutoPruneDelay(
        goog.gears.LogStore.DEFAULT_PRUNE_KEEPER_COUNT_,
        goog.gears.LogStore.DEFAULT_AUTOPRUNE_INTERVAL_MILLIS_);
  }
  this.delay_.fire();
};


/**
 * Disable scheduled pruning.
 */
goog.gears.LogStore.prototype.stopAutoPrune = function() {
  if (this.delay_) {
    this.delay_.stop();
  }
};


/**
 * @return {boolean} True iff auto prune timer is active.
 */
goog.gears.LogStore.prototype.isAutoPruneActive = function() {
  return !!this.delay_ && this.delay_.isActive();
};


/**
 * Prune, and schedule next pruning.
 * @param {?number=} opt_count Number of records of recent hitory to keep.
 * @private
 */
goog.gears.LogStore.prototype.autoPrune_ = function(opt_count) {
  this.pruneBeforeCount(opt_count);
  this.delay_.start();
};


/**
 * Keep some number of most recent log records and delete all older ones.
 * @param {?number=} opt_count Number of records of recent history to keep. If
 *     unspecified, we use #goog.gears.LogStore.DEFAULT_PRUNE_KEEPER_COUNT_.
 *     Pass in 0 to delete all log records.
 */
goog.gears.LogStore.prototype.pruneBeforeCount = function(opt_count) {
  if (!this.getDatabaseInternal()) {
    return;
  }
  var count = typeof opt_count == 'number' ?
      opt_count : goog.gears.LogStore.DEFAULT_PRUNE_KEEPER_COUNT_;
  this.logger_.info('pruning before ' + count + ' records ago');
  this.flush();
  this.getDatabaseInternal().execute('DELETE FROM ' + this.tableName_ +
      ' WHERE id <= ((SELECT MAX(id) FROM ' + this.tableName_ + ') - ?)',
      count);
};


/**
 * Delete log record #id and all older records.
 * @param {number} sequenceNumber ID before which we delete all records.
 */
goog.gears.LogStore.prototype.pruneBeforeSequenceNumber =
    function(sequenceNumber) {
  if (!this.getDatabaseInternal()) {
    return;
  }
  this.logger_.info('pruning before sequence number ' + sequenceNumber);
  this.flush();
  this.getDatabaseInternal().execute(
      'DELETE FROM ' + this.tableName_ + ' WHERE id <= ?',
      sequenceNumber);
};


/**
 * Whether we are currently capturing logger output.
 * @return {boolean} Whether we are currently capturing logger output.
 */
goog.gears.LogStore.prototype.isCapturing = function() {
  return this.isCapturing_;
};


/**
 * Sets whether we are currently capturing logger output.
 * @param {boolean} capturing Whether to capture logger output.
 */
goog.gears.LogStore.prototype.setCapturing = function(capturing) {
  if (capturing != this.isCapturing_) {
    this.isCapturing_ = capturing;

    // Attach or detach handler from the root logger.
    var rootLogger = goog.debug.LogManager.getRoot();
    if (capturing) {
      rootLogger.addHandler(this.publishHandler_);
      this.logger_.info('enabled');
    } else {
      this.logger_.info('disabling');
      rootLogger.removeHandler(this.publishHandler_);
    }
  }
};


/**
 * Adds a log record.
 * @param {goog.debug.LogRecord} logRecord the LogRecord.
 */
goog.gears.LogStore.prototype.addLogRecord = function(logRecord) {
  this.records_.push(logRecord);
  this.bufferSize_ += logRecord.getMessage().length;
  var exceptionText = logRecord.getExceptionText();
  if (exceptionText) {
    this.bufferSize_ += exceptionText.length;
  }
  if (this.bufferSize_ >= goog.gears.LogStore.MAX_BUFFER_BYTES_) {
    this.flush();
  }
};


/**
 * Select log records.
 * @param {goog.gears.LogStore.Query} query Query object.
 * @return {Array.<goog.debug.LogRecord>} Selected logs in descending
 *     order of creation time.
 */
goog.gears.LogStore.prototype.select = function(query) {
  if (!this.getDatabaseInternal()) {
    // This should only occur if we've been disposed.
    return [];
  }
  this.flush();

  // TODO(user) Perhaps have Query object build this SQL string so we can
  // omit unneeded WHERE clauses.
  var statement =
      'SELECT id, millis, level, msg, logger, exception, exceptionText' +
      ' FROM ' + this.tableName_ +
      ' WHERE level >= ? AND millis >= ? AND millis <= ?' +
      ' AND msg like ? and logger like ?' +
      ' ORDER BY id DESC LIMIT ?';
  var rows = this.getDatabaseInternal().queryObjectArray(statement,
      query.level.value, query.minMillis, query.maxMillis,
      query.msgLike, query.loggerLike, query.limit);

  var result = Array(rows.length);
  for (var i = rows.length - 1; i >= 0; i--) {
    var row = rows[i];

    // Parse fields, allowing for invalid values.
    var sequenceNumber = Number(row['id']) || 0;
    var level = goog.debug.Logger.Level.getPredefinedLevelByValue(
        Number(row['level']) || 0);
    var msg = row['msg'] || '';
    var loggerName = row['logger'] || '';
    var millis = Number(row['millis']) || 0;
    var serializedException = row['exception'];
    var exception = serializedException ?
        goog.json.parse(serializedException) : null;
    var exceptionText = row['exceptionText'] || '';

    // Create record.
    var record = new goog.debug.LogRecord(level, msg, loggerName,
        millis, sequenceNumber);
    if (exception) {
      record.setException(exception);
      record.setExceptionText(exceptionText);
    }

    result[i] = record;
  }
  return result;
};


/** @override */
goog.gears.LogStore.prototype.disposeInternal = function() {
  this.flush();

  goog.gears.LogStore.superClass_.disposeInternal.call(this);

  if (this.delay_) {
    this.delay_.dispose();
    this.delay_ = null;
  }
};



/**
 * Query to select log records.
 * @constructor
 */
goog.gears.LogStore.Query = function() {
};


/**
 * Minimum logging level.
 * @type {goog.debug.Logger.Level}
 */
goog.gears.LogStore.Query.prototype.level = goog.debug.Logger.Level.ALL;


/**
 * Minimum timestamp, inclusive.
 * @type {number}
 */
goog.gears.LogStore.Query.prototype.minMillis = -1;


/**
 * Maximum timestamp, inclusive.
 * @type {number}
 */
goog.gears.LogStore.Query.prototype.maxMillis = Infinity;


/**
 * Message 'like' pattern.
 * See http://www.sqlite.org/lang_expr.html#likeFunc for 'like' syntax.
 * @type {string}
 */
goog.gears.LogStore.Query.prototype.msgLike = '%';


/**
 * Logger name 'like' pattern.
 * See http://www.sqlite.org/lang_expr.html#likeFunc for 'like' syntax.
 * @type {string}
 */
goog.gears.LogStore.Query.prototype.loggerLike = '%';


/**
 * Max # recent records to return. -1 means no limit.
 * @type {number}
 */
goog.gears.LogStore.Query.prototype.limit = -1;