log_utils.py 6.3 KB
Newer Older
liuzhe-lz's avatar
liuzhe-lz committed
1
2
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
fishyds's avatar
fishyds committed
3

4
5
6
7
8
9
10
import os
import sys
import json
import logging
import logging.handlers
import time
import threading
SparkSnail's avatar
SparkSnail committed
11
import re
12

fishyds's avatar
fishyds committed
13
14
from datetime import datetime
from enum import Enum, unique
15
16
17
18
from logging import StreamHandler

from queue import Queue

chicm-ms's avatar
chicm-ms committed
19
from .rest_utils import rest_post
20
from .url_utils import gen_send_stdout_url
21
22
from .commands import CommandType

fishyds's avatar
fishyds committed
23
24
25

@unique
class LogType(Enum):
26
    Trace = 'TRACE'
fishyds's avatar
fishyds committed
27
28
29
30
    Debug = 'DEBUG'
    Info = 'INFO'
    Warning = 'WARNING'
    Error = 'ERROR'
31
    Fatal = 'FATAL'
fishyds's avatar
fishyds committed
32

33

34
35
36
37
38
@unique
class StdOutputType(Enum):
    Stdout = 'stdout',
    Stderr = 'stderr'

39

fishyds's avatar
fishyds committed
40
41
42
def nni_log(log_type, log_message):
    '''Log message into stdout'''
    dt = datetime.now()
43
    print('[{0}] {1} {2}'.format(dt, log_type.value, log_message), flush=True)
44

45

46
class NNIRestLogHanlder(StreamHandler):
47
    def __init__(self, host, port, tag, trial_id, channel, std_output_type=StdOutputType.Stdout):
48
49
50
51
52
        StreamHandler.__init__(self)
        self.host = host
        self.port = port
        self.tag = tag
        self.std_output_type = std_output_type
53
54
        self.trial_id = trial_id
        self.channel = channel
55
56
57
58
59
60
61
62
63
64
        self.orig_stdout = sys.__stdout__
        self.orig_stderr = sys.__stderr__

    def emit(self, record):
        log_entry = {}
        log_entry['tag'] = self.tag
        log_entry['stdOutputType'] = self.std_output_type.name
        log_entry['msg'] = self.format(record)

        try:
65
66
67
68
69
70
            if self.channel is None:
                rest_post(gen_send_stdout_url(self.host, self.port), json.dumps(log_entry), 10, True)
            else:
                if self.trial_id is not None:
                    log_entry["trial"] = self.trial_id
                self.channel.send(CommandType.StdOut, log_entry)
71
72
73
74
        except Exception as e:
            self.orig_stderr.write(str(e) + '\n')
            self.orig_stderr.flush()

75

76
77
78
79
class RemoteLogger(object):
    """
    NNI remote logger
    """
80
81

    def __init__(self, syslog_host, syslog_port, tag, std_output_type, log_collection, trial_id=None, channel=None, log_level=logging.INFO):
82
83
84
85
86
87
        '''
        constructor
        '''
        self.logger = logging.getLogger('nni_syslog_{}'.format(tag))
        self.log_level = log_level
        self.logger.setLevel(self.log_level)
88
89
90
        self.pipeReader = None
        self.handler = NNIRestLogHanlder(syslog_host, syslog_port, tag, trial_id, channel)
        self.logger.addHandler(self.handler)
91
92
93
94
        if std_output_type == StdOutputType.Stdout:
            self.orig_stdout = sys.__stdout__
        else:
            self.orig_stdout = sys.__stderr__
SparkSnail's avatar
SparkSnail committed
95
        self.log_collection = log_collection
96
97
98
99
100

    def get_pipelog_reader(self):
        '''
        Get pipe for remote logger
        '''
101
102
        self.pipeReader = PipeLogReader(self.logger, self.log_collection, logging.INFO)
        return self.pipeReader
103

SparkSnail's avatar
SparkSnail committed
104
105
106
107
108
109
110
    def flush(self):
        '''
        Add flush in handler
        '''
        for handler in self.logger.handlers:
            handler.flush()

111
112
113
114
115
116
117
118
119
    def write(self, buf):
        '''
        Write buffer data into logger/stdout
        '''
        for line in buf.rstrip().splitlines():
            self.orig_stdout.write(line.rstrip() + '\n')
            self.orig_stdout.flush()
            try:
                self.logger.log(self.log_level, line.rstrip())
chicm-ms's avatar
chicm-ms committed
120
            except Exception:
121
122
                pass

123
124
125
126
127
128
129
130
131
132
133
    def close(self):
        '''
        Close handlers and resources
        '''
        if self.pipeReader is not None:
            self.pipeReader.set_process_exit()
        for handler in self.logger.handlers:
            handler.close()
            self.logger.removeHandler(handler)


134
135
136
137
class PipeLogReader(threading.Thread):
    """
    The reader thread reads log data from pipe
    """
138

SparkSnail's avatar
SparkSnail committed
139
    def __init__(self, logger, log_collection, log_level=logging.INFO):
140
141
142
143
144
145
146
147
148
149
150
151
        """Setup the object with a logger and a loglevel
        and start the thread
        """
        threading.Thread.__init__(self)
        self.queue = Queue()
        self.logger = logger
        self.daemon = False
        self.log_level = log_level
        self.fdRead, self.fdWrite = os.pipe()
        self.pipeReader = os.fdopen(self.fdRead)
        self.orig_stdout = sys.__stdout__
        self._is_read_completed = False
152
        self.process_exit = False
SparkSnail's avatar
SparkSnail committed
153
        self.log_collection = log_collection
154
        self.log_pattern = re.compile(r'NNISDK_MEb\'.*\'$')
155
156
157
158
159

        def _populateQueue(stream, queue):
            '''
            Collect lines from 'stream' and put them in 'quque'.
            '''
160
            time.sleep(1)
161
            while True:
162
                cur_process_exit = self.process_exit
163
164
165
166
                try:
                    line = self.queue.get(True, 5)
                    try:
                        self.logger.log(self.log_level, line.rstrip())
chicm-ms's avatar
chicm-ms committed
167
                    except Exception:
168
                        pass
chicm-ms's avatar
chicm-ms committed
169
                except Exception:
170
                    if cur_process_exit == True:
171
172
                        self._is_read_completed = True
                        break
173

chicm-ms's avatar
chicm-ms committed
174
        self.pip_log_reader_thread = threading.Thread(target=_populateQueue, args=(self.pipeReader, self.queue))
175
176
177
178
179
180
181
182
183
184
185
        self.pip_log_reader_thread.daemon = True
        self.start()
        self.pip_log_reader_thread.start()

    def fileno(self):
        """Return the write file descriptor of the pipe
        """
        return self.fdWrite

    def run(self):
        """Run the thread, logging everything.
SparkSnail's avatar
SparkSnail committed
186
           If the log_collection is 'none', the log content will not be enqueued
187
188
        """
        for line in iter(self.pipeReader.readline, ''):
SparkSnail's avatar
SparkSnail committed
189
190
            self.orig_stdout.write(line.rstrip() + '\n')
            self.orig_stdout.flush()
191

SparkSnail's avatar
SparkSnail committed
192
            if self.log_collection == 'none':
193
194
195
196
197
198
                search_result = self.log_pattern.search(line)
                if search_result:
                    metrics = search_result.group(0)
                    self.queue.put(metrics+'\n')
            else:
                self.queue.put(line)
199

200
201
202
203
204
205
206
207
208
209
210
        self.pipeReader.close()

    def close(self):
        """Close the write end of the pipe.
        """
        os.close(self.fdWrite)

    @property
    def is_read_completed(self):
        """Return if read is completed
        """
211
        return self._is_read_completed
212

213
214
    def set_process_exit(self):
        self.process_exit = True
chicm-ms's avatar
chicm-ms committed
215
        return self.process_exit