log.ts 4.15 KB
Newer Older
Deshui Yu's avatar
Deshui Yu committed
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
/**
 * Copyright (c) Microsoft Corporation
 * All rights reserved.
 *
 * MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

'use strict';
/* tslint:disable:no-any */

import * as fs from 'fs';
import * as path from 'path';
import { Writable } from 'stream';
import { WritableStreamBuffer } from 'stream-buffers';
import { format } from 'util';
import * as component from '../common/component';
import { getLogDir } from './utils';

const CRITICAL: number = 1;
const ERROR: number = 2;
const WARNING: number = 3;
const INFO: number = 4;
const DEBUG: number = 5;

class BufferSerialEmitter {
    private buffer: Buffer;
    private emitting: boolean;
    private writable: Writable;

    constructor(writable: Writable) {
Zejun Lin's avatar
Zejun Lin committed
43
        this.buffer = Buffer.alloc(0);
Deshui Yu's avatar
Deshui Yu committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
        this.emitting = false;
        this.writable = writable;
    }

    public feed(buffer: Buffer): void {
        this.buffer = Buffer.concat([this.buffer, buffer]);
        if (!this.emitting) {
            this.emit();
        }
    }

    private emit(): void {
        this.emitting = true;
        this.writable.write(this.buffer, () => {
            if (this.buffer.length === 0) {
                this.emitting = false;
            } else {
                this.emit();
            }
        });
Zejun Lin's avatar
Zejun Lin committed
64
        this.buffer = Buffer.alloc(0);
Deshui Yu's avatar
Deshui Yu committed
65
66
67
68
69
70
71
72
    }
}

@component.Singleton
class Logger {
    private DEFAULT_LOGFILE: string = path.join(getLogDir(), 'nnimanager.log');
    private level: number = DEBUG;
    private bufferSerialEmitter: BufferSerialEmitter;
Gems Guo's avatar
Gems Guo committed
73
    private writable: Writable;
Deshui Yu's avatar
Deshui Yu committed
74
75
76
77
78
79

    constructor(fileName?: string) {
        let logFile: string | undefined = fileName;
        if (logFile === undefined) {
            logFile = this.DEFAULT_LOGFILE;
        }
Gems Guo's avatar
Gems Guo committed
80
        this.writable = fs.createWriteStream(logFile, {
Deshui Yu's avatar
Deshui Yu committed
81
82
83
            flags: 'a+',
            encoding: 'utf8',
            autoClose: true
84
        });
Gems Guo's avatar
Gems Guo committed
85
        this.bufferSerialEmitter = new BufferSerialEmitter(this.writable);
86
87
88
    }

    public close() {
Gems Guo's avatar
Gems Guo committed
89
        this.writable.destroy();
Deshui Yu's avatar
Deshui Yu committed
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
    }

    public debug(...param: any[]): void {
        if (this.level >= DEBUG) {
            this.log('DEBUG', param);
        }
    }

    public info(...param: any[]): void {
        if (this.level >= INFO) {
            this.log('INFO', param);
        }
    }

    public warning(...param: any[]): void {
        if (this.level >= WARNING) {
            this.log('WARNING', param);
        }
    }

    public error(...param: any[]): void {
        if (this.level >= ERROR) {
            this.log('ERROR', param);
        }
    }

    public critical(...param: any[]): void {
        this.log('CRITICAL', param);
    }

    private log(level: string, param: any[]): void {
        const buffer: WritableStreamBuffer = new WritableStreamBuffer();
        buffer.write(`[${(new Date()).toISOString()}] ${level} `);
goooxu's avatar
goooxu committed
123
        buffer.write(format(null, param));
Deshui Yu's avatar
Deshui Yu committed
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
        buffer.write('\n');
        buffer.end();
        this.bufferSerialEmitter.feed(buffer.getContents());
    }
}

function getLogger(fileName?: string): Logger {
    component.Container.bind(Logger).provider({
        get: (): Logger => new Logger(fileName)
    });

    return component.get(Logger);
}

export { Logger, getLogger };