UNPKG

1.05 kBJavaScriptView Raw
1'use strict';
2
3/**
4 * Access log plugin
5 * Provides basic request logging with console output
6 * @module Crixalis
7 * @submodule access
8 * @for Controller
9 */
10
11var sprintf = require('sprintf').sprintf;
12
13function colorize (string, color) {
14 return '\u001b[' + color + 'm' + string + '\u001b[39m';
15}
16
17module.exports = function (options) {
18 options = Object(options);
19
20 /* Check stdout descriptor type */
21 if (!options.hasOwnProperty('color')) {
22 options.color = require('tty').isatty(1);
23 }
24
25 this.on('destroy', function () {
26 var time = (Date.now() - this.start) / 1000,
27 code = String(this.code || 200);
28
29 if (!(options.color === false)) {
30 switch (code[0]) {
31 case '1':
32 case '2':
33 /* Green */
34 code = colorize(code, 32);
35 break;
36
37 case '3':
38 /* Yellow */
39 code = colorize(code, 33);
40 break;
41
42 case '4':
43 case '5':
44 /* Red */
45 code = colorize(code, 31);
46 break;
47 }
48 }
49
50 console.log(sprintf(
51 "%1.3f %s %-4s %s %s",
52 time, code, this.method, this.address, this.req.url)
53 );
54 });
55};