log_utils.py 5.39 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
fishyds's avatar
fishyds committed
21
22
23

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

31
32
33
34
35
@unique
class StdOutputType(Enum):
    Stdout = 'stdout',
    Stderr = 'stderr'

fishyds's avatar
fishyds committed
36
37
38
def nni_log(log_type, log_message):
    '''Log message into stdout'''
    dt = datetime.now()
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    print('[{0}] {1} {2}'.format(dt, log_type.value, log_message))

class NNIRestLogHanlder(StreamHandler):
    def __init__(self, host, port, tag, std_output_type=StdOutputType.Stdout):
        StreamHandler.__init__(self)
        self.host = host
        self.port = port
        self.tag = tag
        self.std_output_type = std_output_type
        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:
chicm-ms's avatar
chicm-ms committed
58
            rest_post(gen_send_stdout_url(self.host, self.port), json.dumps(log_entry), 10, True)
59
60
61
62
63
64
65
66
        except Exception as e:
            self.orig_stderr.write(str(e) + '\n')
            self.orig_stderr.flush()

class RemoteLogger(object):
    """
    NNI remote logger
    """
SparkSnail's avatar
SparkSnail committed
67
    def __init__(self, syslog_host, syslog_port, tag, std_output_type, log_collection, log_level=logging.INFO):
68
69
70
71
72
73
74
75
76
77
78
79
        '''
        constructor
        '''
        self.logger = logging.getLogger('nni_syslog_{}'.format(tag))
        self.log_level = log_level
        self.logger.setLevel(self.log_level)
        handler = NNIRestLogHanlder(syslog_host, syslog_port, tag)
        self.logger.addHandler(handler)
        if std_output_type == StdOutputType.Stdout:
            self.orig_stdout = sys.__stdout__
        else:
            self.orig_stdout = sys.__stderr__
SparkSnail's avatar
SparkSnail committed
80
        self.log_collection = log_collection
81
82
83
84
85

    def get_pipelog_reader(self):
        '''
        Get pipe for remote logger
        '''
SparkSnail's avatar
SparkSnail committed
86
        return PipeLogReader(self.logger, self.log_collection, logging.INFO)
87
88
89
90
91
92
93
94
95
96

    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
97
            except Exception:
98
99
100
101
102
103
                pass

class PipeLogReader(threading.Thread):
    """
    The reader thread reads log data from pipe
    """
SparkSnail's avatar
SparkSnail committed
104
    def __init__(self, logger, log_collection, log_level=logging.INFO):
105
106
107
108
109
110
111
112
113
114
115
116
        """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
117
        self.process_exit = False
SparkSnail's avatar
SparkSnail committed
118
        self.log_collection = log_collection
119
        self.log_pattern = re.compile(r'NNISDK_MEb\'.*\'$')
120
121
122
123
124
125

        def _populateQueue(stream, queue):
            '''
            Collect lines from 'stream' and put them in 'quque'.
            '''
            time.sleep(5)
126
            while True:
127
                cur_process_exit = self.process_exit
128
129
130
131
                try:
                    line = self.queue.get(True, 5)
                    try:
                        self.logger.log(self.log_level, line.rstrip())
chicm-ms's avatar
chicm-ms committed
132
                    except Exception:
133
                        pass
chicm-ms's avatar
chicm-ms committed
134
                except Exception:
135
                    if cur_process_exit == True:
136
137
                        self._is_read_completed = True
                        break
138

chicm-ms's avatar
chicm-ms committed
139
        self.pip_log_reader_thread = threading.Thread(target=_populateQueue, args=(self.pipeReader, self.queue))
140
141
142
143
144
145
146
147
148
149
150
        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
151
           If the log_collection is 'none', the log content will not be enqueued
152
153
        """
        for line in iter(self.pipeReader.readline, ''):
SparkSnail's avatar
SparkSnail committed
154
155
            self.orig_stdout.write(line.rstrip() + '\n')
            self.orig_stdout.flush()
156

SparkSnail's avatar
SparkSnail committed
157
            if self.log_collection == 'none':
158
159
160
161
162
163
                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)
164

165
166
167
168
169
170
171
172
173
174
175
        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
        """
176
        return self._is_read_completed
177

178
179
    def set_process_exit(self):
        self.process_exit = True
chicm-ms's avatar
chicm-ms committed
180
        return self.process_exit