Esempio n. 1
0
    def log_record_to_envelope(self, record):
        envelope = Envelope(
            iKey=self.options.instrumentation_key,
            tags=dict(utils.azure_monitor_context),
            time=utils.timestamp_to_iso_str(record.created),
        )
        envelope.tags['ai.operation.id'] = getattr(
            record,
            'traceId',
            '00000000000000000000000000000000',
        )
        envelope.tags['ai.operation.parentId'] = '|{}.{}.'.format(
            envelope.tags['ai.operation.id'],
            getattr(record, 'spanId', '0000000000000000'),
        )
        properties = {
            'process': record.processName,
            'module': record.module,
            'fileName': record.pathname,
            'lineNumber': record.lineno,
            'level': record.levelname,
        }
        if record.exc_info:
            exctype, _value, tb = record.exc_info
            callstack = []
            level = 0
            for fileName, line, method, _text in traceback.extract_tb(tb):
                callstack.append({
                    'level': level,
                    'method': method,
                    'fileName': fileName,
                    'line': line,
                })
                level += 1
            callstack.reverse()

            envelope.name = 'Microsoft.ApplicationInsights.Exception'
            data = ExceptionData(
                exceptions=[{
                    'id': 1,
                    'outerId': 0,
                    'typeName': exctype.__name__,
                    'message': self.format(record),
                    'hasFullStack': True,
                    'parsedStack': callstack,
                }],
                severityLevel=max(0, record.levelno - 1) // 10,
                properties=properties,
            )
            envelope.data = Data(baseData=data, baseType='ExceptionData')
        else:
            envelope.name = 'Microsoft.ApplicationInsights.Message'
            data = Message(
                message=self.format(record),
                severityLevel=max(0, record.levelno - 1) // 10,
                properties=properties,
            )
            envelope.data = Data(baseData=data, baseType='MessageData')
        return envelope
Esempio n. 2
0
    def log_record_to_envelope(self, record):
        envelope = create_envelope(self.options.instrumentation_key, record)

        properties = {
            'process': record.processName,
            'module': record.module,
            'fileName': record.pathname,
            'lineNumber': record.lineno,
            'level': record.levelname,
        }
        if (hasattr(record, 'custom_dimensions')
                and isinstance(record.custom_dimensions, dict)):
            properties.update(record.custom_dimensions)

        if record.exc_info:
            exctype, _value, tb = record.exc_info
            callstack = []
            level = 0
            for fileName, line, method, _text in traceback.extract_tb(tb):
                callstack.append({
                    'level': level,
                    'method': method,
                    'fileName': fileName,
                    'line': line,
                })
                level += 1
            callstack.reverse()

            envelope.name = 'Microsoft.ApplicationInsights.Exception'
            data = ExceptionData(
                exceptions=[{
                    'id': 1,
                    'outerId': 0,
                    'typeName': exctype.__name__,
                    'message': self.format(record),
                    'hasFullStack': True,
                    'parsedStack': callstack,
                }],
                severityLevel=max(0, record.levelno - 1) // 10,
                properties=properties,
            )
            envelope.data = Data(baseData=data, baseType='ExceptionData')
        else:
            envelope.name = 'Microsoft.ApplicationInsights.Message'
            data = Message(
                message=self.format(record),
                severityLevel=max(0, record.levelno - 1) // 10,
                properties=properties,
            )
            envelope.data = Data(baseData=data, baseType='MessageData')
        return envelope
    def span_data_to_envelope(self, sd):
        envelope = Envelope(
            iKey=self.options.instrumentation_key,
            tags=dict(utils.azure_monitor_context),
            time=sd.start_time,
        )

        envelope.tags['ai.operation.id'] = sd.context.trace_id
        if sd.parent_span_id:
            envelope.tags['ai.operation.parentId'] = '{}'.format(
                sd.parent_span_id, )
        if sd.span_kind == SpanKind.SERVER:
            if ERROR_MESSAGE in sd.attributes:
                envelope.name = 'Microsoft.ApplicationInsights.Exception'
                data = ExceptionData(exceptions=[{
                    'id':
                    1,
                    'outerId':
                    '{}'.format(sd.span_id),
                    'typeName':
                    sd.attributes.get(ERROR_NAME, ''),
                    'message':
                    sd.attributes[ERROR_MESSAGE],
                    'hasFullStack':
                    STACKTRACE in sd.attributes,
                    'parsedStack':
                    sd.attributes.get(STACKTRACE, None)
                }], )
                envelope.data = Data(baseData=data, baseType='ExceptionData')
                yield envelope

            envelope.name = 'Microsoft.ApplicationInsights.Request'
            data = Request(
                id='{}'.format(sd.span_id),
                duration=utils.timestamp_to_duration(
                    sd.start_time,
                    sd.end_time,
                ),
                responseCode=str(sd.status.code),
                success=False,  # Modify based off attributes or status
                properties={},
            )
            envelope.data = Data(baseData=data, baseType='RequestData')
            data.name = ''
            if HTTP_METHOD in sd.attributes:
                data.name = sd.attributes[HTTP_METHOD]
            if HTTP_ROUTE in sd.attributes:
                data.name = data.name + ' ' + sd.attributes[HTTP_ROUTE]
                envelope.tags['ai.operation.name'] = data.name
                data.properties['request.name'] = data.name
            elif HTTP_PATH in sd.attributes:
                data.properties['request.name'] = data.name + \
                    ' ' + sd.attributes[HTTP_PATH]
            if HTTP_URL in sd.attributes:
                data.url = sd.attributes[HTTP_URL]
                data.properties['request.url'] = sd.attributes[HTTP_URL]
            if HTTP_STATUS_CODE in sd.attributes:
                status_code = sd.attributes[HTTP_STATUS_CODE]
                data.responseCode = str(status_code)
                data.success = (status_code >= 200 and status_code <= 399)
            elif sd.status.code == 0:
                data.success = True
        else:
            envelope.name = \
                'Microsoft.ApplicationInsights.RemoteDependency'
            data = RemoteDependency(
                name=sd.name,  # TODO
                id='{}'.format(sd.span_id),
                resultCode=str(sd.status.code),
                duration=utils.timestamp_to_duration(
                    sd.start_time,
                    sd.end_time,
                ),
                success=False,  # Modify based off attributes or status
                properties={},
            )
            envelope.data = Data(
                baseData=data,
                baseType='RemoteDependencyData',
            )
            if sd.span_kind == SpanKind.CLIENT:
                data.type = sd.attributes.get('component')
                if HTTP_URL in sd.attributes:
                    url = sd.attributes[HTTP_URL]
                    # TODO: error handling, probably put scheme as well
                    data.data = url
                    parse_url = urlparse(url)
                    # target matches authority (host:port)
                    data.target = parse_url.netloc
                    if HTTP_METHOD in sd.attributes:
                        # name is METHOD/path
                        data.name = sd.attributes[HTTP_METHOD] \
                            + ' ' + parse_url.path
                if HTTP_STATUS_CODE in sd.attributes:
                    status_code = sd.attributes[HTTP_STATUS_CODE]
                    data.resultCode = str(status_code)
                    data.success = 200 <= status_code < 400
                elif sd.status.code == 0:
                    data.success = True
            else:
                data.type = 'INPROC'
                data.success = True
        if sd.links:
            links = []
            for link in sd.links:
                links.append({
                    "operation_Id": link.trace_id,
                    "id": link.span_id
                })
            data.properties["_MS.links"] = json.dumps(links)
        # TODO: tracestate, tags
        for key in sd.attributes:
            # This removes redundant data from ApplicationInsights
            if key.startswith('http.'):
                continue
            data.properties[key] = sd.attributes[key]
        yield envelope