def test_track_event_with_merged_context_properties_works_as_expected( self): key = '99999999-9999-9999-9999-999999999999' sender = MockTelemetrySender() queue = channel.SynchronousQueue(sender) chan = channel.TelemetryChannel(queue=queue) chan.context.properties['foo'] = 'bar' client1 = TelemetryClient(key, chan) client1.context.device = None client1.context.properties['x'] = 42 client2 = TelemetryClient(key, chan) client2.context.device = None client2.context.properties['x'] = 84 client1.track_event('test 1') client1.flush() sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' actual = json.dumps(sender.data.write()) expected = '{"ver": 1, "name": "Microsoft.ApplicationInsights.Event", "time": "TIME_PLACEHOLDER", "sampleRate": 100.0, "iKey": "99999999-9999-9999-9999-999999999999", "tags": {"ai.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER"}, "data": {"baseType": "EventData", "baseData": {"ver": 2, "name": "test 1", "properties": {"foo": "bar", "x": 42}}}}' self.maxDiff = None self.assertEqual(expected, actual) client2.track_event('test 2') client2.flush() sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' actual = json.dumps(sender.data.write()) expected = '{"ver": 1, "name": "Microsoft.ApplicationInsights.Event", "time": "TIME_PLACEHOLDER", "sampleRate": 100.0, "iKey": "99999999-9999-9999-9999-999999999999", "tags": {"ai.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER"}, "data": {"baseType": "EventData", "baseData": {"ver": 2, "name": "test 2", "properties": {"foo": "bar", "x": 84}}}}' self.assertEqual(expected, actual)
def _init_exception_logging(self, app): """ Sets up exception logging unless ``APPINSIGHTS_DISABLE_EXCEPTION_LOGGING`` is set in the Flask config. Args: app (flask.Flask). the Flask application for which to initialize the extension. """ enabled = not app.config.get(CONF_DISABLE_EXCEPTION_LOGGING, False) if not enabled: return if self._key_grantee: self._exception_telemetry_client_grantee = TelemetryClient( self._key_grantee, telemetry_channel=self._channel) if self._key_ai4e: self._exception_telemetry_client_ai4e = TelemetryClient( self._key_ai4e, telemetry_channel=self._channel) @app.errorhandler(Exception) def exception_handler(exception): try: raise exception except Exception: if self._exception_telemetry_client_grantee: self._exception_telemetry_client_grantee.track_exception() if self._exception_telemetry_client_ai4e: self._exception_telemetry_client_ai4e.track_exception() finally: raise exception
def test_track_event_with_common_processor_two_clients(self): def process(data, context): data.properties["NEW_PROP"] = "MYPROP" context.user.id = "BOTUSER" context.session.id = "BOTSESSION" return True key = '99999999-9999-9999-9999-999999999999' sender = MockTelemetrySender() queue = channel.SynchronousQueue(sender) chan = channel.TelemetryChannel(queue=queue) chan.context.properties['foo'] = 'bar' client1 = TelemetryClient(key, chan) client1.add_telemetry_processor(process) client1.context.device = None client1.context.properties['x'] = 42 client2 = TelemetryClient(key, chan) client2.add_telemetry_processor(process) client2.context.device = None client2.context.properties['x'] = 84 client1.track_event('test 1') client1.flush() sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' sender.data.tags['ai.device.id'] = "DEVICE_ID_PLACEHOLDER" sender.data.tags['ai.device.locale'] = "DEVICE_LOCALE_PLACEHOLDER" sender.data.tags[ 'ai.device.osVersion'] = "DEVICE_OS_VERSION_PLACEHOLDER" sender.data.tags['ai.device.type'] = "DEVICE_TYPE_PLACEHOLDER" actual = json.dumps(sender.data.write()) expected = '{"ver": 1, "name": "Microsoft.ApplicationInsights.Event", "time": "TIME_PLACEHOLDER", "sampleRate": 100.0, "iKey": "99999999-9999-9999-9999-999999999999", "tags": {"ai.device.id": "DEVICE_ID_PLACEHOLDER", "ai.device.locale": "DEVICE_LOCALE_PLACEHOLDER", "ai.device.osVersion": "DEVICE_OS_VERSION_PLACEHOLDER", "ai.device.type": "DEVICE_TYPE_PLACEHOLDER", "ai.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER", "ai.session.id": "BOTSESSION", "ai.user.id": "BOTUSER"}, "data": {"baseType": "EventData", "baseData": {"ver": 2, "name": "test 1", "properties": {"NEW_PROP": "MYPROP", "foo": "bar", "x": 42}}}}' self.maxDiff = None self.assertEqual(expected, actual) client2.track_event('test 2') client2.flush() sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' sender.data.tags['ai.device.id'] = "DEVICE_ID_PLACEHOLDER" sender.data.tags['ai.device.locale'] = "DEVICE_LOCALE_PLACEHOLDER" sender.data.tags[ 'ai.device.osVersion'] = "DEVICE_OS_VERSION_PLACEHOLDER" sender.data.tags['ai.device.type'] = "DEVICE_TYPE_PLACEHOLDER" actual = json.dumps(sender.data.write()) expected = '{"ver": 1, "name": "Microsoft.ApplicationInsights.Event", "time": "TIME_PLACEHOLDER", "sampleRate": 100.0, "iKey": "99999999-9999-9999-9999-999999999999", "tags": {"ai.device.id": "DEVICE_ID_PLACEHOLDER", "ai.device.locale": "DEVICE_LOCALE_PLACEHOLDER", "ai.device.osVersion": "DEVICE_OS_VERSION_PLACEHOLDER", "ai.device.type": "DEVICE_TYPE_PLACEHOLDER", "ai.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER", "ai.session.id": "BOTSESSION", "ai.user.id": "BOTUSER"}, "data": {"baseType": "EventData", "baseData": {"ver": 2, "name": "test 2", "properties": {"NEW_PROP": "MYPROP", "foo": "bar", "x": 84}}}}' self.assertEqual(expected, actual)
def __init__(self, tool_name): from applicationinsights import TelemetryClient from azure.servicebus import ServiceBusClient, ServiceBusMessage self.config = task_config() connection_str = os.environ['RAFT_SB_OUT_SAS'] self.sb_client = ServiceBusClient.from_connection_string( connection_str) self.topic_client = self.sb_client.get_topic_sender( self.sb_client._entity_name) self.telemetry_client = TelemetryClient( instrumentation_key=os.environ['RAFT_APP_INSIGHTS_KEY']) self.job_id = os.environ['RAFT_JOB_ID'] self.container_name = os.environ['RAFT_CONTAINER_NAME'] self.tool_name = tool_name self.telemetry_properties = { "jobId": self.job_id, "taskIndex": os.environ['RAFT_TASK_INDEX'], "containerName": self.container_name } self.newSbMessage = ServiceBusMessage
def __init__(self, instrumentation_key: str): self._instrumentation_key = instrumentation_key self._client = TelemetryClient(self._instrumentation_key) # Telemetry Processor def telemetry_processor(data, context): post_data = IntegrationPostData().activity_json # Override session and user id from_prop = post_data['from'] if 'from' in post_data else None user_id = from_prop['id'] if from_prop != None else None channel_id = post_data[ 'channelId'] if 'channelId' in post_data else None conversation = post_data[ 'conversation'] if 'conversation' in post_data else None conversation_id = conversation[ 'id'] if 'id' in conversation else None context.user.id = channel_id + user_id context.session.id = conversation_id # Additional bot-specific properties if 'activityId' in post_data: data.properties["activityId"] = post_data['activityId'] if 'channelId' in post_data: data.properties["channelId"] = post_data['channelId'] if 'activityType' in post_data: data.properties["activityType"] = post_data['activityType'] self._client.add_telemetry_processor(telemetry_processor)
def log_event(self, message): """ Log simple message in strinbg """ obfuscate = ObfuscationUtility(self.seed) client = TelemetryClient(obfuscate.deobfuscate_text(self.ai_code)) client.track_event(message) client.flush()
def log(self, telemetry_instance): """ Log Telemetry instance """ obfuscate = ObfuscationUtility(self.seed) client = TelemetryClient(obfuscate.deobfuscate_text(self.ai_code)) client.track_trace(str(telemetry_instance)) client.flush()
def main(): config = configparser.ConfigParser() config.read(CRED_FILE) subscription_id = str(config['DEFAULT']['AZURE_SUBSCRIPTION_ID']) appinsights_name = str(config['DEFAULT']['APPINSIGHTS_NAME']) resource_group = config['DEFAULT']['RG_NAME'] credentials = ServicePrincipalCredentials( client_id=config['DEFAULT']['azure_client_id'], secret=config['DEFAULT']['azure_client_secret'], tenant=config['DEFAULT']['azure_tenant_id']) try: resource_client = ResourceManagementClient(credentials, subscription_id) except Exception as e: self.logger.error("Getting Azure Infra handlers failed %s" % str(e)) raise e inst_key = get_appinsights_instr_key(resource_group, appinsights_name, credentials, subscription_id) tc = TelemetryClient(inst_key) #logger1.info("[INFO]: Instrumentation key used {}".format(inst_key)) for metric in metric_list: logger1.info("[INFO]: Publishing metrics {}".format(metric)) tc.track_metric(metric, 0) tc.flush() time.sleep(2)
def test_track_exception_works_as_expected(self): sender = MockTelemetrySender() queue = channel.SynchronousQueue(sender) client = TelemetryClient('99999999-9999-9999-9999-999999999999', channel.TelemetryChannel(context=None, queue=queue)) client.context.device = None try: raise Exception("blah") except Exception as e: client.track_exception(*sys.exc_info(), properties={}, measurements={ 'x': 42 }) client.flush() expected = '{"ver": 1, "name": "Microsoft.ApplicationInsights.Exception", "time": "TIME_PLACEHOLDER", "sampleRate": 100.0, "iKey": "99999999-9999-9999-9999-999999999999", "tags": {"ai.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER"}, "data": {"baseType": "ExceptionData", "baseData": {"ver": 2, "handledAt": "UserCode", "exceptions": [{"id": 1, "outerId": 0, "typeName": "Exception", "message": "blah", "hasFullStack": true, "parsedStack": [{"level": 0, "method": "test_track_exception_works_as_expected", "assembly": "Unknown", "fileName": "TestTelemetryClient.py", "line": 0}]}], "measurements": {"x": 42}}}}' sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' for item in sender.data.data.base_data.exceptions: for frame in item.parsed_stack: frame.file_name = os.path.basename(frame.file_name) frame.line = 0 actual = json.dumps(sender.data.write()) self.assertEqual(expected, actual) try: raise Exception("blah") except Exception as e: client.track_exception() client.flush() expected = '{"ver": 1, "name": "Microsoft.ApplicationInsights.Exception", "time": "TIME_PLACEHOLDER", "sampleRate": 100.0, "iKey": "99999999-9999-9999-9999-999999999999", "tags": {"ai.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER"}, "data": {"baseType": "ExceptionData", "baseData": {"ver": 2, "handledAt": "UserCode", "exceptions": [{"id": 1, "outerId": 0, "typeName": "Exception", "message": "blah", "hasFullStack": true, "parsedStack": [{"level": 0, "method": "test_track_exception_works_as_expected", "assembly": "Unknown", "fileName": "TestTelemetryClient.py", "line": 0}]}]}}}' sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' for item in sender.data.data.base_data.exceptions: for frame in item.parsed_stack: frame.file_name = os.path.basename(frame.file_name) frame.line = 0 actual = json.dumps(sender.data.write()) self.assertEqual(expected, actual)
def __init__(self): try: self.telemetry = TelemetryClient(IKEY) if os.path.exists("telemetry.config"): config_file = open("telemetry.config", "r") if config_file.read() == "1": self.enable_telemetry = True else: self.enable_telemetry = False else: self.enable_telemetry = self._query_yes_no(PROMPT_TEXT) config_file = open("telemetry.config", "w") if self.enable_telemetry: config_file.write("1") self.telemetry.track_event("yes", { "device": DEVICE, "language": LANGUAGE }) else: config_file.write("0") self.telemetry.context.location.ip = "0.0.0.0" self.telemetry.track_event("no", { "device": DEVICE, "language": LANGUAGE }) self.telemetry.flush() except: pass
def get_telemetry_client(appInsightsInstrumentationKey): if appInsightsInstrumentationKey: client = TelemetryClient(appInsightsInstrumentationKey) client.context.operation.id = str(uuid.uuid4()) return client else: return None
def _init_exception_logging(self, app): """ Sets up exception logging unless ``APPINSIGHTS_DISABLE_EXCEPTION_LOGGING`` is set in the Flask config. Args: app (flask.Flask). the Flask application for which to initialize the extension. """ enabled = not app.config.get(CONF_DISABLE_EXCEPTION_LOGGING, False) if not enabled: return exception_telemetry_client = TelemetryClient( self._key, telemetry_channel=self._channel) @app.errorhandler(Exception) def exception_handler(exception): exception_telemetry_client.track_exception( type=type(exception), value=exception, tb=exception.__traceback__) raise exception self._exception_telemetry_client = exception_telemetry_client
def __init__(self, pool_id, node_id, refresh_interval=_DEFAULT_STATS_UPDATE_INTERVAL, app_insights_key=None): self.pool_id = pool_id self.node_id = node_id self.telemetry_client = None self.first_collect = True self.refresh_interval = refresh_interval self.disk = IOThroughputAggregator() self.network = IOThroughputAggregator() if app_insights_key or 'APP_INSIGHTS_INSTRUMENTATION_KEY' in os.environ or 'APP_INSIGHTS_KEY' in os.environ: key = (app_insights_key or os.environ.get('APP_INSIGHTS_INSTRUMENTATION_KEY') or os.environ.get('APP_INSIGHTS_KEY')) logger.info( "Detected instrumentation key. Will upload stats to app insights" ) self.telemetry_client = TelemetryClient(key) context = self.telemetry_client.context context.application.id = 'AzureBatchInsights' context.application.ver = VERSION context.device.model = "BatchNode" context.device.role_name = self.pool_id context.device.role_instance = self.node_id else: logger.info( "No instrumentation key detected. Cannot upload to app insights." + "Make sure you have the APP_INSIGHTS_INSTRUMENTATION_KEY environment variable setup" )
def test_track_dependency_works_as_expected(self): def process(data, context): data.properties["NEW_PROP"] = "MYPROP" context.user.id = "BOTUSER" context.session.id = "BOTSESSION" return True sender = MockTelemetrySender() queue = channel.SynchronousQueue(sender) client = TelemetryClient( channel.TelemetryChannel(context=None, queue=queue)) client.add_telemetry_processor(process) client.context.instrumentation_key = '99999999-9999-9999-9999-999999999999' client.context.device = None client.track_dependency('test', 'COMMAND_PLACEHOLDER', 'HTTP', 'localhost', 13, True, 200, {'foo': 'bar'}, {'x': 42}, 'ID_PLACEHOLDER') client.flush() expected = '{"ver": 1, "name": "Microsoft.ApplicationInsights.RemoteDependency", "time": "TIME_PLACEHOLDER", "sampleRate": 100.0, "iKey": "99999999-9999-9999-9999-999999999999", "tags": {"ai.device.id": "DEVICE_ID_PLACEHOLDER", "ai.device.locale": "DEVICE_LOCALE_PLACEHOLDER", "ai.device.osVersion": "DEVICE_OS_VERSION_PLACEHOLDER", "ai.device.type": "DEVICE_TYPE_PLACEHOLDER", "ai.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER", "ai.session.id": "BOTSESSION", "ai.user.id": "BOTUSER"}, "data": {"baseType": "RemoteDependencyData", "baseData": {"ver": 2, "name": "test", "id": "ID_PLACEHOLDER", "resultCode": "200", "duration": "00:00:00.013", "success": true, "data": "COMMAND_PLACEHOLDER", "target": "localhost", "type": "HTTP", "properties": {"NEW_PROP": "MYPROP", "foo": "bar"}, "measurements": {"x": 42}}}}' sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' sender.data.tags['ai.device.id'] = "DEVICE_ID_PLACEHOLDER" sender.data.tags['ai.device.locale'] = "DEVICE_LOCALE_PLACEHOLDER" sender.data.tags[ 'ai.device.osVersion'] = "DEVICE_OS_VERSION_PLACEHOLDER" sender.data.tags['ai.device.type'] = "DEVICE_TYPE_PLACEHOLDER" actual = json.dumps(sender.data.write()) self.maxDiff = None self.assertEqual(expected, actual)
def main(event: func.EventGridEvent): result = json.dumps({ 'id': event.id, 'data': event.get_json(), 'topic': event.topic, 'subject': event.subject, 'event_type': event.event_type, }) logging.info('{} Python EventGrid trigger processed an event:{}'.format(LOG_MESSAGE_HEADER ,result)) get_config_values() regexp = re.compile(EVENT_SUBJECT_FILTER_REGEX) if regexp.search(event.subject): # Check if file path match criteria tc = TelemetryClient(APP_INSIGHT_ID) tc.context.application.ver = '1.0' tc.context.properties["PROCESS_PROGRAM"]=PROCESS_PROGRAM_NAME tc.context.properties["PROCESS_START"]=time.time() tc.track_trace('{} STRAT RUN EVENTGRID INGEST TELEMETRY JSON DATA from folder {} '.format(LOG_MESSAGE_HEADER,result)) tc.flush() configfile_block_blob_service = BlockBlobService(account_name=CONFIG_FILE_BLOB_ACCOUNT, account_key=CONFIG_FILE_BLOB_KEY) cleanfile_block_blob_service = BlockBlobService(account_name=CLEAN_FILE_BLOB_ACCOUNT, account_key=CLEAN_FILE_BLOB_KEY) filepath=get_file_path(event.subject) container_name=get_container_name(event.subject) config_file_name=get_filename(filepath) logging.info('{} filepath: {}'.format(LOG_MESSAGE_HEADER,filepath)) logging.info('{} container_name: {}'.format(LOG_MESSAGE_HEADER, container_name)) config_file_name_utf8, filesize,vm_uuid,deploy_uuid,config_uuid=generate_UTF8_config_json(configfile_block_blob_service,CONFIG_FILE_CONTAINER,filepath,cleanfile_block_blob_service,CLEAN_FILE_CONTAINER ) ingest_to_ADX(config_file_name_utf8, cleanfile_block_blob_service, CLEAN_FILE_CONTAINER, CLEAN_FILE_BLOB_ACCOUNT,filesize,tc,vm_uuid,deploy_uuid,config_uuid) else: logging.info("{} Subject : {} does not match regular express {}. Skip process. ".format(LOG_MESSAGE_HEADER,event.subject,EVENT_SUBJECT_FILTER_REGEX))
def test_track_metric_works_as_expected(self): def process(data, context): data.properties["NEW_PROP"] = "MYPROP" context.user.id = "BOTUSER" context.session.id = "BOTSESSION" return True sender = MockTelemetrySender() queue = channel.SynchronousQueue(sender) client = TelemetryClient( '99999999-9999-9999-9999-999999999999', channel.TelemetryChannel(context=None, queue=queue)) client.add_telemetry_processor(process) client.context.device = None client.track_metric('metric', 42, channel.contracts.DataPointType.aggregation, 13, 1, 123, 111, {'foo': 'bar'}) client.flush() expected = '{"ver": 1, "name": "Microsoft.ApplicationInsights.Metric", "time": "TIME_PLACEHOLDER", "sampleRate": 100.0, "iKey": "99999999-9999-9999-9999-999999999999", "tags": {"ai.device.id": "DEVICE_ID_PLACEHOLDER", "ai.device.locale": "DEVICE_LOCALE_PLACEHOLDER", "ai.device.osVersion": "DEVICE_OS_VERSION_PLACEHOLDER", "ai.device.type": "DEVICE_TYPE_PLACEHOLDER", "ai.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER", "ai.session.id": "BOTSESSION", "ai.user.id": "BOTUSER"}, "data": {"baseType": "MetricData", "baseData": {"ver": 2, "metrics": [{"name": "metric", "kind": 1, "value": 42, "count": 13, "min": 1, "max": 123, "stdDev": 111}], "properties": {"NEW_PROP": "MYPROP", "foo": "bar"}}}}' sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' sender.data.tags['ai.device.id'] = "DEVICE_ID_PLACEHOLDER" sender.data.tags['ai.device.locale'] = "DEVICE_LOCALE_PLACEHOLDER" sender.data.tags[ 'ai.device.osVersion'] = "DEVICE_OS_VERSION_PLACEHOLDER" sender.data.tags['ai.device.type'] = "DEVICE_TYPE_PLACEHOLDER" actual = json.dumps(sender.data.write()) self.maxDiff = None self.assertEqual(expected, actual)
def upload(data_to_save): from applicationinsights import TelemetryClient from applicationinsights.exceptions import enable client = TelemetryClient(INSTRUMENTATION_KEY) enable(INSTRUMENTATION_KEY) if in_diagnostic_mode(): sys.stdout.write('Telemetry upload begins\n') try: data_to_save = json.loads(data_to_save.replace("'", '"')) except Exception as err: # pylint: disable=broad-except if in_diagnostic_mode(): sys.stdout.write('{}/n'.format(str(err))) sys.stdout.write('Raw [{}]/n'.format(data_to_save)) for record in data_to_save: client.track_event(record['name'], record['properties']) client.flush() if in_diagnostic_mode(): json.dump(data_to_save, sys.stdout, indent=2, sort_keys=True) sys.stdout.write('\nTelemetry upload completes\n')
def intercept_excepthook(type, value, traceback): client = TelemetryClient('temp_key', telemetry_channel) for instrumentation_key in enabled_instrumentation_keys: client.context.instrumentation_key = instrumentation_key client.track_exception(type, value, traceback) client.flush() original_excepthook(type, value, traceback)
def __init__(self): self.tc = TelemetryClient(APP_INSIGHTS_KEY) self.user_id = USER_ID self.app_version = pkg_resources.require('oml')[0].version self.python_version = platform.python_version() self.platform = platform.platform() self.timestamp = str(datetime.utcnow())
def __init__(self): # State of the telemetry self.__enable_telemetry = True self.telemetry_client = TelemetryClient("__AIKEY__") self.telemetry_state = dict.fromkeys( [name for name, _ in TelemetryEvent.__members__.items()], False) self.extension_name = "Device Simulator Express"
def test_track_event_modifes_options(self): def process(data, context): context.user.id = "BOTUSER" context.session.id = "BOTSESSION" return True sender = MockTelemetrySender() queue = channel.SynchronousQueue(sender) client = TelemetryClient( '99999999-9999-9999-9999-999999999999', channel.TelemetryChannel(context=None, queue=queue)) client.add_telemetry_processor(process) client.context.device = None client.context.properties['foo'] = 'bar' client.track_event('test') client.flush() expected = '{"ver": 1, "name": "Microsoft.ApplicationInsights.Event", "time": "TIME_PLACEHOLDER", "sampleRate": 100.0, "iKey": "99999999-9999-9999-9999-999999999999", "tags": {"ai.device.id": "DEVICE_ID_PLACEHOLDER", "ai.device.locale": "DEVICE_LOCALE_PLACEHOLDER", "ai.device.osVersion": "DEVICE_OS_VERSION_PLACEHOLDER", "ai.device.type": "DEVICE_TYPE_PLACEHOLDER", "ai.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER", "ai.session.id": "BOTSESSION", "ai.user.id": "BOTUSER"}, "data": {"baseType": "EventData", "baseData": {"ver": 2, "name": "test", "properties": {"foo": "bar"}}}}' sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' sender.data.tags['ai.device.id'] = "DEVICE_ID_PLACEHOLDER" sender.data.tags['ai.device.locale'] = "DEVICE_LOCALE_PLACEHOLDER" sender.data.tags[ 'ai.device.osVersion'] = "DEVICE_OS_VERSION_PLACEHOLDER" sender.data.tags['ai.device.type'] = "DEVICE_TYPE_PLACEHOLDER" actual = json.dumps(sender.data.write()) self.maxDiff = None self.assertEqual(expected, actual)
def test_track_pageview_works_as_expected(self): def process(data, context): data.properties["NEW_PROP"] = "MYPROP" context.user.id = "BOTUSER" context.session.id = "BOTSESSION" return True sender = MockTelemetrySender() queue = channel.SynchronousQueue(sender) client = TelemetryClient( '99999999-9999-9999-9999-999999999999', channel.TelemetryChannel(context=None, queue=queue)) client.add_telemetry_processor(process) client.context.device = None client.track_pageview('test', 'http://tempuri.org', 13, {'foo': 'bar'}, {'x': 42}) client.flush() expected = '{"ver": 1, "name": "Microsoft.ApplicationInsights.PageView", "time": "TIME_PLACEHOLDER", "sampleRate": 100.0, "iKey": "99999999-9999-9999-9999-999999999999", "tags": {"ai.device.id": "DEVICE_ID_PLACEHOLDER", "ai.device.locale": "DEVICE_LOCALE_PLACEHOLDER", "ai.device.osVersion": "DEVICE_OS_VERSION_PLACEHOLDER", "ai.device.type": "DEVICE_TYPE_PLACEHOLDER", "ai.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER", "ai.session.id": "BOTSESSION", "ai.user.id": "BOTUSER"}, "data": {"baseType": "PageViewData", "baseData": {"ver": 2, "url": "http://tempuri.org", "name": "test", "duration": 13, "properties": {"NEW_PROP": "MYPROP", "foo": "bar"}, "measurements": {"x": 42}}}}' sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' sender.data.tags['ai.device.id'] = "DEVICE_ID_PLACEHOLDER" sender.data.tags['ai.device.locale'] = "DEVICE_LOCALE_PLACEHOLDER" sender.data.tags[ 'ai.device.osVersion'] = "DEVICE_OS_VERSION_PLACEHOLDER" sender.data.tags['ai.device.type'] = "DEVICE_TYPE_PLACEHOLDER" actual = json.dumps(sender.data.write()) self.maxDiff = None self.assertEqual(expected, actual)
def _initialize(self): if self.tc is not None: return self.instrumentation_key = AppInsightsHelper.get_instrumentation_key( self.config['url']) self.tc = TelemetryClient(self.instrumentation_key) self.subscription_id = local_session( self.ctx.policy.session_factory).get_subscription_id()
def main(): """Main programm""" args = parse_cli_args() tc = TelemetryClient(args.appinsights_key) while True: res = perform_log(tc, args.__dict__) sleep(args.log_interval)
def __init__(self, instrumentation_key: str, telemetry_client: TelemetryClient = None): self._instrumentation_key = instrumentation_key self._client = (telemetry_client if telemetry_client is not None else TelemetryClient(self._instrumentation_key)) # Telemetry Processor self._client.add_telemetry_processor(bot_telemetry_processor)
def client(self): ctx = _app_ctx_stack.top if ctx is not None: if not hasattr(ctx, 'appinsight_client'): ctx.appinsight_client = TelemetryClient( current_app.config[CONFIG_KEY_INSTRUMENTATION_KEY], telemetry_channel=TelemetryChannel( queue=AsynchronousQueue(AsynchronousSender()))) return ctx.appinsight_client
def NewTelemetryClient (applicationId, operationId="", parentOperationId=""): tc = TelemetryClient(instrumentationKey) tc.context.application.id = applicationId tc.context.application.ver = '0.0.1' tc.context.device.id = 'Databricks notebook' tc.context.operation.id = operationId tc.context.operation.parentId = parentOperationId return tc
def send_specific(): filename = filedialog.askopenfilename(initialdir="/", title="selectfile", filetypes=(("executables", "*.exe"), ("allfiles", "*.*"))) tc = TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>') tc.track_event(filename, {'foo': 'bar'}, {'baz': 42}) tc.flush() messagebox.showinfo("updates", "sent")
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') metricspath = req.params.get('metricspath') forceinsert = req.params.get('forceinsert') if not metricspath: try: req_body = req.get_json() except ValueError: pass else: metricspath = req_body.get('metricspath') forceinsert = req_body.get('forceinsert') if forceinsert is None: forceinsert = '' if metricspath: scode = 400 msg = 'Something Wrong, this is Default Message' #print (metricspath) try: scode, msg = process(metricspath, forceinsert) except Exception as e: error_class = e.__class__.__name__ detail = e.args[0] cl, exc, tb = sys.exc_info() lastCallStack = traceback.extract_tb(tb)[-1] fileName = lastCallStack[0] lineNum = lastCallStack[1] funcName = lastCallStack[2] errMsg = "File \"{}\", line {}, in {}: [{}] {}".format( fileName, lineNum, funcName, error_class, detail) print("Unexpected error:", sys.exc_info()[0]) traceback.print_exc() msg = errMsg + traceback.format_exc() tc = TelemetryClient('') tc.context.application.ver = '1.0' tc.context.properties["PROCESS_PROGRAM"] = "BATCH_CSV_V001a" tc.context.properties["DATA_FOLDER"] = metricspath tc.track_trace(msg) tc.flush() scode = 500 return func.HttpResponse(f"Proccessed {metricspath}! " + msg, status_code=scode) else: return func.HttpResponse( "Please pass a metricspath on the query string or in the request body", status_code=400)
def __init__(self, appinsightskey, monitor_list, upload_interval_seconds=60, quiet=False): self.monitors = monitor_list self.telemetry = [] self.telemetry_client = TelemetryClient(appinsightskey) self.upload_interval_seconds = upload_interval_seconds self.quiet = quiet