log.ts 4.81 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
/**
 * 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';
29
import { getExperimentStartupInfo } from './experimentStartupInfo';
Deshui Yu's avatar
Deshui Yu committed
30
31
import { getLogDir } from './utils';

32
const FATAL: number = 1;
Deshui Yu's avatar
Deshui Yu committed
33
34
35
36
const ERROR: number = 2;
const WARNING: number = 3;
const INFO: number = 4;
const DEBUG: number = 5;
37
38
39
40
const TRACE: number = 6;

const logLevelNameMap: Map<string, number> = new Map([['fatal', FATAL],
    ['error', ERROR], ['warning', WARNING], ['info', INFO], ['debug', DEBUG], ['trace', TRACE]]);
Deshui Yu's avatar
Deshui Yu committed
41
42
43
44
45
46
47

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

    constructor(writable: Writable) {
Zejun Lin's avatar
Zejun Lin committed
48
        this.buffer = Buffer.alloc(0);
Deshui Yu's avatar
Deshui Yu committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
        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
69
        this.buffer = Buffer.alloc(0);
Deshui Yu's avatar
Deshui Yu committed
70
71
72
73
74
75
    }
}

@component.Singleton
class Logger {
    private DEFAULT_LOGFILE: string = path.join(getLogDir(), 'nnimanager.log');
chicm-ms's avatar
chicm-ms committed
76
    private level: number = INFO;
Deshui Yu's avatar
Deshui Yu committed
77
    private bufferSerialEmitter: BufferSerialEmitter;
Gems Guo's avatar
Gems Guo committed
78
    private writable: Writable;
Deshui Yu's avatar
Deshui Yu committed
79
80
81
82
83
84

    constructor(fileName?: string) {
        let logFile: string | undefined = fileName;
        if (logFile === undefined) {
            logFile = this.DEFAULT_LOGFILE;
        }
Gems Guo's avatar
Gems Guo committed
85
        this.writable = fs.createWriteStream(logFile, {
Deshui Yu's avatar
Deshui Yu committed
86
87
88
            flags: 'a+',
            encoding: 'utf8',
            autoClose: true
89
        });
Gems Guo's avatar
Gems Guo committed
90
        this.bufferSerialEmitter = new BufferSerialEmitter(this.writable);
91
92
93
94
95
96
97

        const logLevelName: string = getExperimentStartupInfo()
                                    .getLogLevel();
        const logLevel: number | undefined = logLevelNameMap.get(logLevelName);
        if (logLevel !== undefined) {
            this.level = logLevel;
        }
98
99
100
    }

    public close() {
Gems Guo's avatar
Gems Guo committed
101
        this.writable.destroy();
Deshui Yu's avatar
Deshui Yu committed
102
103
    }

104
105
106
107
108
109
    public trace(...param: any[]): void {
        if (this.level >= TRACE) {
            this.log('TRACE', param);
        }
    }

Deshui Yu's avatar
Deshui Yu committed
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
    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);
        }
    }

134
135
    public fatal(...param: any[]): void {
        this.log('FATAL', param);
Deshui Yu's avatar
Deshui Yu committed
136
137
138
139
140
    }

    private log(level: string, param: any[]): void {
        const buffer: WritableStreamBuffer = new WritableStreamBuffer();
        buffer.write(`[${(new Date()).toISOString()}] ${level} `);
goooxu's avatar
goooxu committed
141
        buffer.write(format(null, param));
Deshui Yu's avatar
Deshui Yu committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
        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);
}

chicm-ms's avatar
chicm-ms committed
156
export { Logger, getLogger, logLevelNameMap };