applicationinsights-0.11.0/0000755000076600000240000000000013145103565016067 5ustar alexbstaff00000000000000applicationinsights-0.11.0/applicationinsights/0000755000076600000240000000000013145103565022143 5ustar alexbstaff00000000000000applicationinsights-0.11.0/applicationinsights/__init__.py0000644000076600000240000000015713143420775024262 0ustar alexbstaff00000000000000from .TelemetryClient import TelemetryClient from . import channel from . import logging from . import requestsapplicationinsights-0.11.0/applicationinsights/channel/0000755000076600000240000000000013145103565023553 5ustar alexbstaff00000000000000applicationinsights-0.11.0/applicationinsights/channel/__init__.py0000644000076600000240000000064113143421424025660 0ustar alexbstaff00000000000000from .AsynchronousQueue import AsynchronousQueue from .AsynchronousSender import AsynchronousSender from .SenderBase import SenderBase from .QueueBase import QueueBase from .SynchronousQueue import SynchronousQueue from .SynchronousSender import SynchronousSender from .TelemetryChannel import TelemetryChannel from .TelemetryContext import TelemetryContext from .NullSender import NullSender from . import contracts applicationinsights-0.11.0/applicationinsights/channel/AsynchronousQueue.py0000644000076600000240000000317713143420775027640 0ustar alexbstaff00000000000000from .QueueBase import QueueBase from threading import Event class AsynchronousQueue(QueueBase): """An asynchronous queue for use in conjunction with the :class:`AsynchronousSender`. The queue will notify the sender that it needs to pick up items when it reaches :func:`max_queue_length`, or when the consumer calls :func:`flush` via the :func:`flush_notification` event. """ def __init__(self, sender): """Initializes a new instance of the class. Args: sender (:class:`SenderBase`) the sender object that will be used in conjunction with this queue. """ self._flush_notification = Event() QueueBase.__init__(self, sender) @property def flush_notification(self): """The flush notification :class:`Event` that the :func:`sender` will use to get notified that a flush is needed. Returns: :class:`Event`. object that the :func:`sender` can wait on. """ return self._flush_notification def put(self, item): """Adds the passed in item object to the queue and notifies the :func:`sender` to start an asynchronous send operation by calling :func:`start`. Args: item (:class:`contracts.Envelope`) the telemetry envelope object to send to the service. """ QueueBase.put(self, item) if self.sender: self.sender.start() def flush(self): """Flushes the current queue by notifying the :func:`sender` via the :func:`flush_notification` event. """ self._flush_notification.set() if self.sender: self.sender.start() applicationinsights-0.11.0/applicationinsights/channel/AsynchronousSender.py0000644000076600000240000001247313143420775027773 0ustar alexbstaff00000000000000from .SenderBase import SenderBase from threading import Lock, Thread class AsynchronousSender(SenderBase): """An asynchronous sender that works in conjunction with the :class:`AsynchronousQueue`. The sender object will start a worker thread that will pull items from the :func:`queue`. The thread will be created when the client calls :func:`start` and will check for queue items every :func:`send_interval` seconds. The worker thread can also be forced to check the queue by setting the :func:`flush_notification` event. - If no items are found, the thread will go back to sleep. - If items are found, the worker thread will send items to the specified service in batches of :func:`send_buffer_size`. If no queue items are found for :func:`send_time` seconds, the worker thread will shut down (and :func:`start` will need to be called again). """ def __init__(self, service_endpoint_uri='https://dc.services.visualstudio.com/v2/track'): """Initializes a new instance of the class. Args: sender (String) service_endpoint_uri the address of the service to send telemetry data to. """ self._send_interval = 1.0 self._send_remaining_time = 0 self._send_time = 3.0 self._lock_send_remaining_time = Lock() SenderBase.__init__(self, service_endpoint_uri) @property def send_interval(self): """The time span in seconds at which the the worker thread will check the :func:`queue` for items (defaults to: 1.0). Args: value (int) the interval in seconds. Returns: int. the interval in seconds. """ return self._send_interval @send_interval.setter def send_interval(self, value): """The time span in seconds at which the the worker thread will check the :func:`queue` for items (defaults to: 1.0). Args: value (int) the interval in seconds. Returns: int. the interval in seconds. """ self._send_interval = value @property def send_time(self): """The time span in seconds at which the the worker thread will check the :func:`queue` for items (defaults to: 1.0). Args: value (int) the interval in seconds. Returns: int. the interval in seconds. """ return self._send_time @send_time.setter def send_time(self, value): """The time span in seconds at which the the worker thread will check the :func:`queue` for items (defaults to: 1.0). Args: value (int) the interval in seconds. Returns: int. the interval in seconds. """ self._send_time = value def start(self): """Starts a new sender thread if none is not already there """ with self._lock_send_remaining_time: if self._send_remaining_time <= 0.0: local_send_interval = self._send_interval if self._send_interval < 0.1: local_send_interval = 0.1 self._send_remaining_time = self._send_time if self._send_remaining_time < local_send_interval: self._send_remaining_time = local_send_interval thread = Thread(target=self._run) thread.daemon = True thread.start() def stop(self): """Gracefully stops the sender thread if one is there. """ with self._lock_send_remaining_time: self._send_remaining_time = 0.0 def _run(self): # save the queue locally local_queue = self._queue if not local_queue: self.stop() return # fix up the send interval (can't be lower than 100ms) local_send_interval = self._send_interval if self._send_interval < 0.1: local_send_interval = 0.1 local_send_time = self._send_time if local_send_time < local_send_interval: local_send_time = local_send_interval while True: while True: # get at most send_buffer_size items from the queue counter = self._send_buffer_size data = [] while counter > 0: item = local_queue.get() if not item: break data.append(item) counter -= 1 # if we didn't get any items from the queue, we're done here if len(data) == 0: break # reset the send time with self._lock_send_remaining_time: self._send_remaining_time = local_send_time # finally send the data self.send(data) # wait at most send_interval (or until we get signalled) result = local_queue.flush_notification.wait(local_send_interval) if result: local_queue.flush_notification.clear() continue # decrement the remaining time local_remaining_time = 0 with self._lock_send_remaining_time: self._send_remaining_time -= local_send_interval local_remaining_time = self._send_remaining_time if local_remaining_time <= 0: break applicationinsights-0.11.0/applicationinsights/channel/contracts/0000755000076600000240000000000013145103565025553 5ustar alexbstaff00000000000000applicationinsights-0.11.0/applicationinsights/channel/contracts/__init__.py0000644000076600000240000000150513143420775027670 0ustar alexbstaff00000000000000from .Data import Data from .Envelope import Envelope from .DependencyKind import DependencyKind from .SeverityLevel import SeverityLevel from .DataPoint import DataPoint from .MetricData import MetricData from .RemoteDependencyData import RemoteDependencyData from .RequestData import RequestData from .StackFrame import StackFrame from .ExceptionDetails import ExceptionDetails from .ExceptionData import ExceptionData from .MessageData import MessageData from .EventData import EventData from .PageViewData import PageViewData from .DataPointType import DataPointType from .DependencySourceType import DependencySourceType from .Application import Application from .Device import Device from .Location import Location from .Operation import Operation from .Session import Session from .User import User from .Internal import Internal applicationinsights-0.11.0/applicationinsights/channel/contracts/Application.py0000644000076600000240000000277413143420775030405 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class Application(object): """Data contract class for type Application. """ _defaults = collections.OrderedDict([ ('ai.application.ver', None) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { } self._initialize() @property def ver(self): """The ver property. Returns: (string). the property value. (defaults to: None) """ if 'ai.application.ver' in self._values: return self._values['ai.application.ver'] return self._defaults['ai.application.ver'] @ver.setter def ver(self, value): """The ver property. Args: value (string). the property value. """ if value == self._defaults['ai.application.ver'] and 'ai.application.ver' in self._values: del self._values['ai.application.ver'] else: self._values['ai.application.ver'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/Data.py0000644000076600000240000000366213143420775027010 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class Data(object): """Data contract class for type Data. """ _defaults = collections.OrderedDict([ ('baseType', None), ('baseData', None) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { 'baseData': None } self._initialize() @property def base_type(self): """The base_type property. Returns: (string). the property value. (defaults to: None) """ if 'baseType' in self._values: return self._values['baseType'] return self._defaults['baseType'] @base_type.setter def base_type(self, value): """The base_type property. Args: value (string). the property value. """ if value == self._defaults['baseType'] and 'baseType' in self._values: del self._values['baseType'] else: self._values['baseType'] = value @property def base_data(self): """The base_data property. Returns: (object). the property value. (defaults to: None) """ return self._values['baseData'] @base_data.setter def base_data(self, value): """The base_data property. Args: value (object). the property value. """ self._values['baseData'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/DataPoint.py0000644000076600000240000001175413143420775030023 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object from .DataPointType import DataPointType class DataPoint(object): """Data contract class for type DataPoint. """ _defaults = collections.OrderedDict([ ('name', None), ('kind', DataPointType.measurement), ('value', None), ('count', None), ('min', None), ('max', None), ('stdDev', None) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { 'name': None, 'kind': DataPointType.measurement, 'value': None, } self._initialize() @property def name(self): """The name property. Returns: (string). the property value. (defaults to: None) """ return self._values['name'] @name.setter def name(self, value): """The name property. Args: value (string). the property value. """ self._values['name'] = value @property def kind(self): """The kind property. Returns: (:class:`DataPointType.measurement`). the property value. (defaults to: DataPointType.measurement) """ if 'kind' in self._values: return self._values['kind'] return self._defaults['kind'] @kind.setter def kind(self, value): """The kind property. Args: value (:class:`DataPointType.measurement`). the property value. """ if value == self._defaults['kind'] and 'kind' in self._values: del self._values['kind'] else: self._values['kind'] = value @property def value(self): """The value property. Returns: (float). the property value. (defaults to: None) """ return self._values['value'] @value.setter def value(self, value): """The value property. Args: value (float). the property value. """ self._values['value'] = value @property def count(self): """The count property. Returns: (int). the property value. (defaults to: None) """ if 'count' in self._values: return self._values['count'] return self._defaults['count'] @count.setter def count(self, value): """The count property. Args: value (int). the property value. """ if value == self._defaults['count'] and 'count' in self._values: del self._values['count'] else: self._values['count'] = value @property def min(self): """The min property. Returns: (float). the property value. (defaults to: None) """ if 'min' in self._values: return self._values['min'] return self._defaults['min'] @min.setter def min(self, value): """The min property. Args: value (float). the property value. """ if value == self._defaults['min'] and 'min' in self._values: del self._values['min'] else: self._values['min'] = value @property def max(self): """The max property. Returns: (float). the property value. (defaults to: None) """ if 'max' in self._values: return self._values['max'] return self._defaults['max'] @max.setter def max(self, value): """The max property. Args: value (float). the property value. """ if value == self._defaults['max'] and 'max' in self._values: del self._values['max'] else: self._values['max'] = value @property def std_dev(self): """The std_dev property. Returns: (float). the property value. (defaults to: None) """ if 'stdDev' in self._values: return self._values['stdDev'] return self._defaults['stdDev'] @std_dev.setter def std_dev(self, value): """The std_dev property. Args: value (float). the property value. """ if value == self._defaults['stdDev'] and 'stdDev' in self._values: del self._values['stdDev'] else: self._values['stdDev'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/DataPointType.py0000644000076600000240000000031613143420775030655 0ustar alexbstaff00000000000000class DataPointType(object): """Data contract class for type DataPointType.""" # Enumeration value measurement measurement = 0 # Enumeration value aggregation aggregation = 1 applicationinsights-0.11.0/applicationinsights/channel/contracts/DependencyKind.py0000644000076600000240000000045413143420775031017 0ustar alexbstaff00000000000000class DependencyKind(object): """Data contract class for type DependencyKind.""" # Enumeration value undefined undefined = 0 # Enumeration value http_only http_only = 1 # Enumeration value http_any http_any = 2 # Enumeration value sql sql = 3 applicationinsights-0.11.0/applicationinsights/channel/contracts/DependencySourceType.py0000644000076600000240000000036713143420775032237 0ustar alexbstaff00000000000000class DependencySourceType(object): """Data contract class for type DependencySourceType.""" # Enumeration value undefined undefined = 0 # Enumeration value aic aic = 1 # Enumeration value apmc apmc = 2 applicationinsights-0.11.0/applicationinsights/channel/contracts/Device.py0000644000076600000240000002614613143420775027340 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class Device(object): """Data contract class for type Device. """ _defaults = collections.OrderedDict([ ('ai.device.id', None), ('ai.device.ip', None), ('ai.device.language', None), ('ai.device.locale', None), ('ai.device.model', None), ('ai.device.network', None), ('ai.device.oemName', None), ('ai.device.os', None), ('ai.device.osVersion', None), ('ai.device.roleInstance', None), ('ai.device.roleName', None), ('ai.device.screenResolution', None), ('ai.device.type', None), ('ai.device.vmName', None) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { } self._initialize() @property def id(self): """The id property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.id' in self._values: return self._values['ai.device.id'] return self._defaults['ai.device.id'] @id.setter def id(self, value): """The id property. Args: value (string). the property value. """ if value == self._defaults['ai.device.id'] and 'ai.device.id' in self._values: del self._values['ai.device.id'] else: self._values['ai.device.id'] = value @property def ip(self): """The ip property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.ip' in self._values: return self._values['ai.device.ip'] return self._defaults['ai.device.ip'] @ip.setter def ip(self, value): """The ip property. Args: value (string). the property value. """ if value == self._defaults['ai.device.ip'] and 'ai.device.ip' in self._values: del self._values['ai.device.ip'] else: self._values['ai.device.ip'] = value @property def language(self): """The language property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.language' in self._values: return self._values['ai.device.language'] return self._defaults['ai.device.language'] @language.setter def language(self, value): """The language property. Args: value (string). the property value. """ if value == self._defaults['ai.device.language'] and 'ai.device.language' in self._values: del self._values['ai.device.language'] else: self._values['ai.device.language'] = value @property def locale(self): """The locale property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.locale' in self._values: return self._values['ai.device.locale'] return self._defaults['ai.device.locale'] @locale.setter def locale(self, value): """The locale property. Args: value (string). the property value. """ if value == self._defaults['ai.device.locale'] and 'ai.device.locale' in self._values: del self._values['ai.device.locale'] else: self._values['ai.device.locale'] = value @property def model(self): """The model property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.model' in self._values: return self._values['ai.device.model'] return self._defaults['ai.device.model'] @model.setter def model(self, value): """The model property. Args: value (string). the property value. """ if value == self._defaults['ai.device.model'] and 'ai.device.model' in self._values: del self._values['ai.device.model'] else: self._values['ai.device.model'] = value @property def network(self): """The network property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.network' in self._values: return self._values['ai.device.network'] return self._defaults['ai.device.network'] @network.setter def network(self, value): """The network property. Args: value (string). the property value. """ if value == self._defaults['ai.device.network'] and 'ai.device.network' in self._values: del self._values['ai.device.network'] else: self._values['ai.device.network'] = value @property def oem_name(self): """The oem_name property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.oemName' in self._values: return self._values['ai.device.oemName'] return self._defaults['ai.device.oemName'] @oem_name.setter def oem_name(self, value): """The oem_name property. Args: value (string). the property value. """ if value == self._defaults['ai.device.oemName'] and 'ai.device.oemName' in self._values: del self._values['ai.device.oemName'] else: self._values['ai.device.oemName'] = value @property def os(self): """The os property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.os' in self._values: return self._values['ai.device.os'] return self._defaults['ai.device.os'] @os.setter def os(self, value): """The os property. Args: value (string). the property value. """ if value == self._defaults['ai.device.os'] and 'ai.device.os' in self._values: del self._values['ai.device.os'] else: self._values['ai.device.os'] = value @property def os_version(self): """The os_version property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.osVersion' in self._values: return self._values['ai.device.osVersion'] return self._defaults['ai.device.osVersion'] @os_version.setter def os_version(self, value): """The os_version property. Args: value (string). the property value. """ if value == self._defaults['ai.device.osVersion'] and 'ai.device.osVersion' in self._values: del self._values['ai.device.osVersion'] else: self._values['ai.device.osVersion'] = value @property def role_instance(self): """The role_instance property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.roleInstance' in self._values: return self._values['ai.device.roleInstance'] return self._defaults['ai.device.roleInstance'] @role_instance.setter def role_instance(self, value): """The role_instance property. Args: value (string). the property value. """ if value == self._defaults['ai.device.roleInstance'] and 'ai.device.roleInstance' in self._values: del self._values['ai.device.roleInstance'] else: self._values['ai.device.roleInstance'] = value @property def role_name(self): """The role_name property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.roleName' in self._values: return self._values['ai.device.roleName'] return self._defaults['ai.device.roleName'] @role_name.setter def role_name(self, value): """The role_name property. Args: value (string). the property value. """ if value == self._defaults['ai.device.roleName'] and 'ai.device.roleName' in self._values: del self._values['ai.device.roleName'] else: self._values['ai.device.roleName'] = value @property def screen_resolution(self): """The screen_resolution property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.screenResolution' in self._values: return self._values['ai.device.screenResolution'] return self._defaults['ai.device.screenResolution'] @screen_resolution.setter def screen_resolution(self, value): """The screen_resolution property. Args: value (string). the property value. """ if value == self._defaults['ai.device.screenResolution'] and 'ai.device.screenResolution' in self._values: del self._values['ai.device.screenResolution'] else: self._values['ai.device.screenResolution'] = value @property def type(self): """The type property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.type' in self._values: return self._values['ai.device.type'] return self._defaults['ai.device.type'] @type.setter def type(self, value): """The type property. Args: value (string). the property value. """ if value == self._defaults['ai.device.type'] and 'ai.device.type' in self._values: del self._values['ai.device.type'] else: self._values['ai.device.type'] = value @property def vm_name(self): """The vm_name property. Returns: (string). the property value. (defaults to: None) """ if 'ai.device.vmName' in self._values: return self._values['ai.device.vmName'] return self._defaults['ai.device.vmName'] @vm_name.setter def vm_name(self, value): """The vm_name property. Args: value (string). the property value. """ if value == self._defaults['ai.device.vmName'] and 'ai.device.vmName' in self._values: del self._values['ai.device.vmName'] else: self._values['ai.device.vmName'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/Envelope.py0000644000076600000240000002410213143420775027704 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class Envelope(object): """Data contract class for type Envelope. """ _defaults = collections.OrderedDict([ ('ver', 1), ('name', None), ('time', None), ('sampleRate', 100.0), ('seq', None), ('iKey', None), ('flags', None), ('deviceId', None), ('os', None), ('osVer', None), ('appId', None), ('appVer', None), ('userId', None), ('tags', {}), ('data', None) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { 'ver': 1, 'name': None, 'time': None, 'sampleRate': 100.0, } self._initialize() @property def ver(self): """The ver property. Returns: (int). the property value. (defaults to: 1) """ if 'ver' in self._values: return self._values['ver'] return self._defaults['ver'] @ver.setter def ver(self, value): """The ver property. Args: value (int). the property value. """ if value == self._defaults['ver'] and 'ver' in self._values: del self._values['ver'] else: self._values['ver'] = value @property def name(self): """The name property. Returns: (string). the property value. (defaults to: None) """ return self._values['name'] @name.setter def name(self, value): """The name property. Args: value (string). the property value. """ self._values['name'] = value @property def time(self): """The time property. Returns: (string). the property value. (defaults to: None) """ return self._values['time'] @time.setter def time(self, value): """The time property. Args: value (string). the property value. """ self._values['time'] = value @property def sample_rate(self): """The sample_rate property. Returns: (float). the property value. (defaults to: 100.0) """ if 'sampleRate' in self._values: return self._values['sampleRate'] return self._defaults['sampleRate'] @sample_rate.setter def sample_rate(self, value): """The sample_rate property. Args: value (float). the property value. """ if value == self._defaults['sampleRate'] and 'sampleRate' in self._values: del self._values['sampleRate'] else: self._values['sampleRate'] = value @property def seq(self): """The seq property. Returns: (string). the property value. (defaults to: None) """ if 'seq' in self._values: return self._values['seq'] return self._defaults['seq'] @seq.setter def seq(self, value): """The seq property. Args: value (string). the property value. """ if value == self._defaults['seq'] and 'seq' in self._values: del self._values['seq'] else: self._values['seq'] = value @property def ikey(self): """The ikey property. Returns: (string). the property value. (defaults to: None) """ if 'iKey' in self._values: return self._values['iKey'] return self._defaults['iKey'] @ikey.setter def ikey(self, value): """The ikey property. Args: value (string). the property value. """ if value == self._defaults['iKey'] and 'iKey' in self._values: del self._values['iKey'] else: self._values['iKey'] = value @property def flags(self): """The flags property. Returns: (int). the property value. (defaults to: None) """ if 'flags' in self._values: return self._values['flags'] return self._defaults['flags'] @flags.setter def flags(self, value): """The flags property. Args: value (int). the property value. """ if value == self._defaults['flags'] and 'flags' in self._values: del self._values['flags'] else: self._values['flags'] = value @property def device_id(self): """The device_id property. Returns: (string). the property value. (defaults to: None) """ if 'deviceId' in self._values: return self._values['deviceId'] return self._defaults['deviceId'] @device_id.setter def device_id(self, value): """The device_id property. Args: value (string). the property value. """ if value == self._defaults['deviceId'] and 'deviceId' in self._values: del self._values['deviceId'] else: self._values['deviceId'] = value @property def os(self): """The os property. Returns: (string). the property value. (defaults to: None) """ if 'os' in self._values: return self._values['os'] return self._defaults['os'] @os.setter def os(self, value): """The os property. Args: value (string). the property value. """ if value == self._defaults['os'] and 'os' in self._values: del self._values['os'] else: self._values['os'] = value @property def os_ver(self): """The os_ver property. Returns: (string). the property value. (defaults to: None) """ if 'osVer' in self._values: return self._values['osVer'] return self._defaults['osVer'] @os_ver.setter def os_ver(self, value): """The os_ver property. Args: value (string). the property value. """ if value == self._defaults['osVer'] and 'osVer' in self._values: del self._values['osVer'] else: self._values['osVer'] = value @property def app_id(self): """The app_id property. Returns: (string). the property value. (defaults to: None) """ if 'appId' in self._values: return self._values['appId'] return self._defaults['appId'] @app_id.setter def app_id(self, value): """The app_id property. Args: value (string). the property value. """ if value == self._defaults['appId'] and 'appId' in self._values: del self._values['appId'] else: self._values['appId'] = value @property def app_ver(self): """The app_ver property. Returns: (string). the property value. (defaults to: None) """ if 'appVer' in self._values: return self._values['appVer'] return self._defaults['appVer'] @app_ver.setter def app_ver(self, value): """The app_ver property. Args: value (string). the property value. """ if value == self._defaults['appVer'] and 'appVer' in self._values: del self._values['appVer'] else: self._values['appVer'] = value @property def user_id(self): """The user_id property. Returns: (string). the property value. (defaults to: None) """ if 'userId' in self._values: return self._values['userId'] return self._defaults['userId'] @user_id.setter def user_id(self, value): """The user_id property. Args: value (string). the property value. """ if value == self._defaults['userId'] and 'userId' in self._values: del self._values['userId'] else: self._values['userId'] = value @property def tags(self): """The tags property. Returns: (hash). the property value. (defaults to: {}) """ if 'tags' in self._values: return self._values['tags'] self._values['tags'] = copy.deepcopy(self._defaults['tags']) return self._values['tags'] @tags.setter def tags(self, value): """The tags property. Args: value (hash). the property value. """ if value == self._defaults['tags'] and 'tags' in self._values: del self._values['tags'] else: self._values['tags'] = value @property def data(self): """The data property. Returns: (object). the property value. (defaults to: None) """ if 'data' in self._values: return self._values['data'] return self._defaults['data'] @data.setter def data(self, value): """The data property. Args: value (object). the property value. """ if value == self._defaults['data'] and 'data' in self._values: del self._values['data'] else: self._values['data'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/EventData.py0000644000076600000240000000650213143420775030006 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class EventData(object): """Data contract class for type EventData. """ ENVELOPE_TYPE_NAME = 'Microsoft.ApplicationInsights.Event' DATA_TYPE_NAME = 'EventData' _defaults = collections.OrderedDict([ ('ver', 2), ('name', None), ('properties', {}), ('measurements', {}) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { 'ver': 2, 'name': None, } self._initialize() @property def ver(self): """The ver property. Returns: (int). the property value. (defaults to: 2) """ return self._values['ver'] @ver.setter def ver(self, value): """The ver property. Args: value (int). the property value. """ self._values['ver'] = value @property def name(self): """The name property. Returns: (string). the property value. (defaults to: None) """ return self._values['name'] @name.setter def name(self, value): """The name property. Args: value (string). the property value. """ self._values['name'] = value @property def properties(self): """The properties property. Returns: (hash). the property value. (defaults to: {}) """ if 'properties' in self._values: return self._values['properties'] self._values['properties'] = copy.deepcopy(self._defaults['properties']) return self._values['properties'] @properties.setter def properties(self, value): """The properties property. Args: value (hash). the property value. """ if value == self._defaults['properties'] and 'properties' in self._values: del self._values['properties'] else: self._values['properties'] = value @property def measurements(self): """The measurements property. Returns: (hash). the property value. (defaults to: {}) """ if 'measurements' in self._values: return self._values['measurements'] self._values['measurements'] = copy.deepcopy(self._defaults['measurements']) return self._values['measurements'] @measurements.setter def measurements(self, value): """The measurements property. Args: value (hash). the property value. """ if value == self._defaults['measurements'] and 'measurements' in self._values: del self._values['measurements'] else: self._values['measurements'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/ExceptionData.py0000644000076600000240000001116113143420775030660 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class ExceptionData(object): """Data contract class for type ExceptionData. """ ENVELOPE_TYPE_NAME = 'Microsoft.ApplicationInsights.Exception' DATA_TYPE_NAME = 'ExceptionData' _defaults = collections.OrderedDict([ ('ver', 2), ('handledAt', None), ('exceptions', []), ('severityLevel', None), ('properties', {}), ('measurements', {}) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { 'ver': 2, 'handledAt': None, 'exceptions': [], } self._initialize() @property def ver(self): """The ver property. Returns: (int). the property value. (defaults to: 2) """ return self._values['ver'] @ver.setter def ver(self, value): """The ver property. Args: value (int). the property value. """ self._values['ver'] = value @property def handled_at(self): """The handled_at property. Returns: (string). the property value. (defaults to: None) """ return self._values['handledAt'] @handled_at.setter def handled_at(self, value): """The handled_at property. Args: value (string). the property value. """ self._values['handledAt'] = value @property def exceptions(self): """The exceptions property. Returns: (list). the property value. (defaults to: []) """ return self._values['exceptions'] @exceptions.setter def exceptions(self, value): """The exceptions property. Args: value (list). the property value. """ self._values['exceptions'] = value @property def severity_level(self): """The severity_level property. Returns: (int). the property value. (defaults to: None) """ if 'severityLevel' in self._values: return self._values['severityLevel'] return self._defaults['severityLevel'] @severity_level.setter def severity_level(self, value): """The severity_level property. Args: value (int). the property value. """ if value == self._defaults['severityLevel'] and 'severityLevel' in self._values: del self._values['severityLevel'] else: self._values['severityLevel'] = value @property def properties(self): """The properties property. Returns: (hash). the property value. (defaults to: {}) """ if 'properties' in self._values: return self._values['properties'] self._values['properties'] = copy.deepcopy(self._defaults['properties']) return self._values['properties'] @properties.setter def properties(self, value): """The properties property. Args: value (hash). the property value. """ if value == self._defaults['properties'] and 'properties' in self._values: del self._values['properties'] else: self._values['properties'] = value @property def measurements(self): """The measurements property. Returns: (hash). the property value. (defaults to: {}) """ if 'measurements' in self._values: return self._values['measurements'] self._values['measurements'] = copy.deepcopy(self._defaults['measurements']) return self._values['measurements'] @measurements.setter def measurements(self, value): """The measurements property. Args: value (hash). the property value. """ if value == self._defaults['measurements'] and 'measurements' in self._values: del self._values['measurements'] else: self._values['measurements'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/ExceptionDetails.py0000644000076600000240000001230313143420775031373 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class ExceptionDetails(object): """Data contract class for type ExceptionDetails. """ _defaults = collections.OrderedDict([ ('id', None), ('outerId', None), ('typeName', None), ('message', None), ('hasFullStack', True), ('stack', None), ('parsedStack', []) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { 'typeName': None, 'message': None, 'hasFullStack': True, } self._initialize() @property def id(self): """The id property. Returns: (int). the property value. (defaults to: None) """ if 'id' in self._values: return self._values['id'] return self._defaults['id'] @id.setter def id(self, value): """The id property. Args: value (int). the property value. """ if value == self._defaults['id'] and 'id' in self._values: del self._values['id'] else: self._values['id'] = value @property def outer_id(self): """The outer_id property. Returns: (int). the property value. (defaults to: None) """ if 'outerId' in self._values: return self._values['outerId'] return self._defaults['outerId'] @outer_id.setter def outer_id(self, value): """The outer_id property. Args: value (int). the property value. """ if value == self._defaults['outerId'] and 'outerId' in self._values: del self._values['outerId'] else: self._values['outerId'] = value @property def type_name(self): """The type_name property. Returns: (string). the property value. (defaults to: None) """ return self._values['typeName'] @type_name.setter def type_name(self, value): """The type_name property. Args: value (string). the property value. """ self._values['typeName'] = value @property def message(self): """The message property. Returns: (string). the property value. (defaults to: None) """ return self._values['message'] @message.setter def message(self, value): """The message property. Args: value (string). the property value. """ self._values['message'] = value @property def has_full_stack(self): """The has_full_stack property. Returns: (bool). the property value. (defaults to: True) """ if 'hasFullStack' in self._values: return self._values['hasFullStack'] return self._defaults['hasFullStack'] @has_full_stack.setter def has_full_stack(self, value): """The has_full_stack property. Args: value (bool). the property value. """ if value == self._defaults['hasFullStack'] and 'hasFullStack' in self._values: del self._values['hasFullStack'] else: self._values['hasFullStack'] = value @property def stack(self): """The stack property. Returns: (string). the property value. (defaults to: None) """ if 'stack' in self._values: return self._values['stack'] return self._defaults['stack'] @stack.setter def stack(self, value): """The stack property. Args: value (string). the property value. """ if value == self._defaults['stack'] and 'stack' in self._values: del self._values['stack'] else: self._values['stack'] = value @property def parsed_stack(self): """The parsed_stack property. Returns: (list). the property value. (defaults to: []) """ if 'parsedStack' in self._values: return self._values['parsedStack'] self._values['parsedStack'] = copy.deepcopy(self._defaults['parsedStack']) return self._values['parsedStack'] @parsed_stack.setter def parsed_stack(self, value): """The parsed_stack property. Args: value (list). the property value. """ if value == self._defaults['parsedStack'] and 'parsedStack' in self._values: del self._values['parsedStack'] else: self._values['parsedStack'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/Internal.py0000644000076600000240000000461213143420775027707 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class Internal(object): """Data contract class for type Internal. """ _defaults = collections.OrderedDict([ ('ai.internal.sdkVersion', None), ('ai.internal.agentVersion', None) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { } self._initialize() @property def sdk_version(self): """The sdk_version property. Returns: (string). the property value. (defaults to: None) """ if 'ai.internal.sdkVersion' in self._values: return self._values['ai.internal.sdkVersion'] return self._defaults['ai.internal.sdkVersion'] @sdk_version.setter def sdk_version(self, value): """The sdk_version property. Args: value (string). the property value. """ if value == self._defaults['ai.internal.sdkVersion'] and 'ai.internal.sdkVersion' in self._values: del self._values['ai.internal.sdkVersion'] else: self._values['ai.internal.sdkVersion'] = value @property def agent_version(self): """The agent_version property. Returns: (string). the property value. (defaults to: None) """ if 'ai.internal.agentVersion' in self._values: return self._values['ai.internal.agentVersion'] return self._defaults['ai.internal.agentVersion'] @agent_version.setter def agent_version(self, value): """The agent_version property. Args: value (string). the property value. """ if value == self._defaults['ai.internal.agentVersion'] and 'ai.internal.agentVersion' in self._values: del self._values['ai.internal.agentVersion'] else: self._values['ai.internal.agentVersion'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/Location.py0000644000076600000240000000272113143420775027702 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class Location(object): """Data contract class for type Location. """ _defaults = collections.OrderedDict([ ('ai.location.ip', None) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { } self._initialize() @property def ip(self): """The ip property. Returns: (string). the property value. (defaults to: None) """ if 'ai.location.ip' in self._values: return self._values['ai.location.ip'] return self._defaults['ai.location.ip'] @ip.setter def ip(self, value): """The ip property. Args: value (string). the property value. """ if value == self._defaults['ai.location.ip'] and 'ai.location.ip' in self._values: del self._values['ai.location.ip'] else: self._values['ai.location.ip'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/MessageData.py0000644000076600000240000000710713143421424030303 0ustar alexbstaff00000000000000import collections import copy import logging from .Utils import _write_complex_object class MessageData(object): """Data contract class for type MessageData. """ ENVELOPE_TYPE_NAME = 'Microsoft.ApplicationInsights.Message' DATA_TYPE_NAME = 'MessageData' PYTHON_LOGGING_LEVELS = { 'DEBUG': 0, 'INFO': 1, 'WARNING': 2, 'ERROR': 3, 'CRITICAL': 4, logging.DEBUG: 0, logging.INFO: 1, logging.WARNING: 2, logging.ERROR: 3, logging.CRITICAL: 4 } _defaults = collections.OrderedDict([ ('ver', 2), ('message', None), ('severityLevel', None), ('properties', {}) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { 'ver': 2, 'message': None, } self._initialize() @property def ver(self): """The ver property. Returns: (int). the property value. (defaults to: 2) """ return self._values['ver'] @ver.setter def ver(self, value): """The ver property. Args: value (int). the property value. """ self._values['ver'] = value @property def message(self): """The message property. Returns: (string). the property value. (defaults to: None) """ return self._values['message'] @message.setter def message(self, value): """The message property. Args: value (string). the property value. """ self._values['message'] = value @property def severity_level(self): """The severity_level property. Returns: (int). the property value. (defaults to: None) """ if 'severityLevel' in self._values: return self._values['severityLevel'] return self._defaults['severityLevel'] @severity_level.setter def severity_level(self, value): """The severity_level property. Args: value (int). the property value. """ if value == self._defaults['severityLevel'] and 'severityLevel' in self._values: del self._values['severityLevel'] else: self._values['severityLevel'] = value @property def properties(self): """The properties property. Returns: (hash). the property value. (defaults to: {}) """ if 'properties' in self._values: return self._values['properties'] self._values['properties'] = copy.deepcopy(self._defaults['properties']) return self._values['properties'] @properties.setter def properties(self, value): """The properties property. Args: value (hash). the property value. """ if value == self._defaults['properties'] and 'properties' in self._values: del self._values['properties'] else: self._values['properties'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/MetricData.py0000644000076600000240000000504513143420775030151 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class MetricData(object): """Data contract class for type MetricData. """ ENVELOPE_TYPE_NAME = 'Microsoft.ApplicationInsights.Metric' DATA_TYPE_NAME = 'MetricData' _defaults = collections.OrderedDict([ ('ver', 2), ('metrics', []), ('properties', {}) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { 'ver': 2, 'metrics': [], } self._initialize() @property def ver(self): """The ver property. Returns: (int). the property value. (defaults to: 2) """ return self._values['ver'] @ver.setter def ver(self, value): """The ver property. Args: value (int). the property value. """ self._values['ver'] = value @property def metrics(self): """The metrics property. Returns: (list). the property value. (defaults to: []) """ return self._values['metrics'] @metrics.setter def metrics(self, value): """The metrics property. Args: value (list). the property value. """ self._values['metrics'] = value @property def properties(self): """The properties property. Returns: (hash). the property value. (defaults to: {}) """ if 'properties' in self._values: return self._values['properties'] self._values['properties'] = copy.deepcopy(self._defaults['properties']) return self._values['properties'] @properties.setter def properties(self, value): """The properties property. Args: value (hash). the property value. """ if value == self._defaults['properties'] and 'properties' in self._values: del self._values['properties'] else: self._values['properties'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/Operation.py0000644000076600000240000000735013143420775030075 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class Operation(object): """Data contract class for type Operation. """ _defaults = collections.OrderedDict([ ('ai.operation.id', None), ('ai.operation.name', None), ('ai.operation.parentId', None), ('ai.operation.rootId', None) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { } self._initialize() @property def id(self): """The id property. Returns: (string). the property value. (defaults to: None) """ if 'ai.operation.id' in self._values: return self._values['ai.operation.id'] return self._defaults['ai.operation.id'] @id.setter def id(self, value): """The id property. Args: value (string). the property value. """ if value == self._defaults['ai.operation.id'] and 'ai.operation.id' in self._values: del self._values['ai.operation.id'] else: self._values['ai.operation.id'] = value @property def name(self): """The name property. Returns: (string). the property value. (defaults to: None) """ if 'ai.operation.name' in self._values: return self._values['ai.operation.name'] return self._defaults['ai.operation.name'] @name.setter def name(self, value): """The name property. Args: value (string). the property value. """ if value == self._defaults['ai.operation.name'] and 'ai.operation.name' in self._values: del self._values['ai.operation.name'] else: self._values['ai.operation.name'] = value @property def parent_id(self): """The parent_id property. Returns: (string). the property value. (defaults to: None) """ if 'ai.operation.parentId' in self._values: return self._values['ai.operation.parentId'] return self._defaults['ai.operation.parentId'] @parent_id.setter def parent_id(self, value): """The parent_id property. Args: value (string). the property value. """ if value == self._defaults['ai.operation.parentId'] and 'ai.operation.parentId' in self._values: del self._values['ai.operation.parentId'] else: self._values['ai.operation.parentId'] = value @property def root_id(self): """The root_id property. Returns: (string). the property value. (defaults to: None) """ if 'ai.operation.rootId' in self._values: return self._values['ai.operation.rootId'] return self._defaults['ai.operation.rootId'] @root_id.setter def root_id(self, value): """The root_id property. Args: value (string). the property value. """ if value == self._defaults['ai.operation.rootId'] and 'ai.operation.rootId' in self._values: del self._values['ai.operation.rootId'] else: self._values['ai.operation.rootId'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/PageViewData.py0000644000076600000240000001116313143420775030433 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class PageViewData(object): """Data contract class for type PageViewData. """ ENVELOPE_TYPE_NAME = 'Microsoft.ApplicationInsights.PageView' DATA_TYPE_NAME = 'PageViewData' _defaults = collections.OrderedDict([ ('ver', 2), ('url', None), ('name', None), ('duration', None), ('properties', {}), ('measurements', {}) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { 'ver': 2, 'name': None, } self._initialize() @property def ver(self): """The ver property. Returns: (int). the property value. (defaults to: 2) """ return self._values['ver'] @ver.setter def ver(self, value): """The ver property. Args: value (int). the property value. """ self._values['ver'] = value @property def url(self): """The url property. Returns: (string). the property value. (defaults to: None) """ if 'url' in self._values: return self._values['url'] return self._defaults['url'] @url.setter def url(self, value): """The url property. Args: value (string). the property value. """ if value == self._defaults['url'] and 'url' in self._values: del self._values['url'] else: self._values['url'] = value @property def name(self): """The name property. Returns: (string). the property value. (defaults to: None) """ return self._values['name'] @name.setter def name(self, value): """The name property. Args: value (string). the property value. """ self._values['name'] = value @property def duration(self): """The duration property. Returns: (string). the property value. (defaults to: None) """ if 'duration' in self._values: return self._values['duration'] return self._defaults['duration'] @duration.setter def duration(self, value): """The duration property. Args: value (string). the property value. """ if value == self._defaults['duration'] and 'duration' in self._values: del self._values['duration'] else: self._values['duration'] = value @property def properties(self): """The properties property. Returns: (hash). the property value. (defaults to: {}) """ if 'properties' in self._values: return self._values['properties'] self._values['properties'] = copy.deepcopy(self._defaults['properties']) return self._values['properties'] @properties.setter def properties(self, value): """The properties property. Args: value (hash). the property value. """ if value == self._defaults['properties'] and 'properties' in self._values: del self._values['properties'] else: self._values['properties'] = value @property def measurements(self): """The measurements property. Returns: (hash). the property value. (defaults to: {}) """ if 'measurements' in self._values: return self._values['measurements'] self._values['measurements'] = copy.deepcopy(self._defaults['measurements']) return self._values['measurements'] @measurements.setter def measurements(self, value): """The measurements property. Args: value (hash). the property value. """ if value == self._defaults['measurements'] and 'measurements' in self._values: del self._values['measurements'] else: self._values['measurements'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/RemoteDependencyData.py0000644000076600000240000002255213143420775032162 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object from .DataPointType import DataPointType from .DependencyKind import DependencyKind from .DependencySourceType import DependencySourceType class RemoteDependencyData(object): """Data contract class for type RemoteDependencyData. """ ENVELOPE_TYPE_NAME = 'Microsoft.ApplicationInsights.RemoteDependency' DATA_TYPE_NAME = 'RemoteDependencyData' _defaults = collections.OrderedDict([ ('ver', 2), ('name', None), ('kind', DataPointType.measurement), ('value', None), ('count', None), ('min', None), ('max', None), ('stdDev', None), ('dependencyKind', DependencyKind.undefined), ('success', True), ('async', None), ('dependencySource', DependencySourceType.undefined), ('properties', {}) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { 'ver': 2, 'name': None, 'kind': DataPointType.measurement, 'value': None, 'dependencyKind': DependencyKind.undefined, 'success': True, 'dependencySource': DependencySourceType.undefined, } self._initialize() @property def ver(self): """The ver property. Returns: (int). the property value. (defaults to: 2) """ return self._values['ver'] @ver.setter def ver(self, value): """The ver property. Args: value (int). the property value. """ self._values['ver'] = value @property def name(self): """The name property. Returns: (string). the property value. (defaults to: None) """ return self._values['name'] @name.setter def name(self, value): """The name property. Args: value (string). the property value. """ self._values['name'] = value @property def kind(self): """The kind property. Returns: (:class:`DataPointType.measurement`). the property value. (defaults to: DataPointType.measurement) """ if 'kind' in self._values: return self._values['kind'] return self._defaults['kind'] @kind.setter def kind(self, value): """The kind property. Args: value (:class:`DataPointType.measurement`). the property value. """ if value == self._defaults['kind'] and 'kind' in self._values: del self._values['kind'] else: self._values['kind'] = value @property def value(self): """The value property. Returns: (float). the property value. (defaults to: None) """ return self._values['value'] @value.setter def value(self, value): """The value property. Args: value (float). the property value. """ self._values['value'] = value @property def count(self): """The count property. Returns: (int). the property value. (defaults to: None) """ if 'count' in self._values: return self._values['count'] return self._defaults['count'] @count.setter def count(self, value): """The count property. Args: value (int). the property value. """ if value == self._defaults['count'] and 'count' in self._values: del self._values['count'] else: self._values['count'] = value @property def min(self): """The min property. Returns: (float). the property value. (defaults to: None) """ if 'min' in self._values: return self._values['min'] return self._defaults['min'] @min.setter def min(self, value): """The min property. Args: value (float). the property value. """ if value == self._defaults['min'] and 'min' in self._values: del self._values['min'] else: self._values['min'] = value @property def max(self): """The max property. Returns: (float). the property value. (defaults to: None) """ if 'max' in self._values: return self._values['max'] return self._defaults['max'] @max.setter def max(self, value): """The max property. Args: value (float). the property value. """ if value == self._defaults['max'] and 'max' in self._values: del self._values['max'] else: self._values['max'] = value @property def std_dev(self): """The std_dev property. Returns: (float). the property value. (defaults to: None) """ if 'stdDev' in self._values: return self._values['stdDev'] return self._defaults['stdDev'] @std_dev.setter def std_dev(self, value): """The std_dev property. Args: value (float). the property value. """ if value == self._defaults['stdDev'] and 'stdDev' in self._values: del self._values['stdDev'] else: self._values['stdDev'] = value @property def dependency_kind(self): """The dependency_kind property. Returns: (:class:`DependencyKind.undefined`). the property value. (defaults to: DependencyKind.undefined) """ return self._values['dependencyKind'] @dependency_kind.setter def dependency_kind(self, value): """The dependency_kind property. Args: value (:class:`DependencyKind.undefined`). the property value. """ self._values['dependencyKind'] = value @property def success(self): """The success property. Returns: (bool). the property value. (defaults to: True) """ if 'success' in self._values: return self._values['success'] return self._defaults['success'] @success.setter def success(self, value): """The success property. Args: value (bool). the property value. """ if value == self._defaults['success'] and 'success' in self._values: del self._values['success'] else: self._values['success'] = value @property def async(self): """The async property. Returns: (bool). the property value. (defaults to: None) """ if 'async' in self._values: return self._values['async'] return self._defaults['async'] @async.setter def async(self, value): """The async property. Args: value (bool). the property value. """ if value == self._defaults['async'] and 'async' in self._values: del self._values['async'] else: self._values['async'] = value @property def dependency_source(self): """The dependency_source property. Returns: (:class:`DependencySourceType.undefined`). the property value. (defaults to: DependencySourceType.undefined) """ if 'dependencySource' in self._values: return self._values['dependencySource'] return self._defaults['dependencySource'] @dependency_source.setter def dependency_source(self, value): """The dependency_source property. Args: value (:class:`DependencySourceType.undefined`). the property value. """ if value == self._defaults['dependencySource'] and 'dependencySource' in self._values: del self._values['dependencySource'] else: self._values['dependencySource'] = value @property def properties(self): """The properties property. Returns: (hash). the property value. (defaults to: {}) """ if 'properties' in self._values: return self._values['properties'] self._values['properties'] = copy.deepcopy(self._defaults['properties']) return self._values['properties'] @properties.setter def properties(self, value): """The properties property. Args: value (hash). the property value. """ if value == self._defaults['properties'] and 'properties' in self._values: del self._values['properties'] else: self._values['properties'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/RequestData.py0000644000076600000240000001635513143420775030364 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class RequestData(object): """Data contract class for type RequestData. """ ENVELOPE_TYPE_NAME = 'Microsoft.ApplicationInsights.Request' DATA_TYPE_NAME = 'RequestData' _defaults = collections.OrderedDict([ ('ver', 2), ('id', None), ('name', None), ('startTime', None), ('duration', None), ('responseCode', None), ('success', None), ('httpMethod', None), ('url', None), ('properties', {}), ('measurements', {}) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { 'ver': 2, 'id': None, 'startTime': None, 'duration': None, 'responseCode': None, 'success': None, } self._initialize() @property def ver(self): """The ver property. Returns: (int). the property value. (defaults to: 2) """ return self._values['ver'] @ver.setter def ver(self, value): """The ver property. Args: value (int). the property value. """ self._values['ver'] = value @property def id(self): """The id property. Returns: (string). the property value. (defaults to: None) """ return self._values['id'] @id.setter def id(self, value): """The id property. Args: value (string). the property value. """ self._values['id'] = value @property def name(self): """The name property. Returns: (string). the property value. (defaults to: None) """ if 'name' in self._values: return self._values['name'] return self._defaults['name'] @name.setter def name(self, value): """The name property. Args: value (string). the property value. """ if value == self._defaults['name'] and 'name' in self._values: del self._values['name'] else: self._values['name'] = value @property def start_time(self): """The start_time property. Returns: (string). the property value. (defaults to: None) """ return self._values['startTime'] @start_time.setter def start_time(self, value): """The start_time property. Args: value (string). the property value. """ self._values['startTime'] = value @property def duration(self): """The duration property. Returns: (string). the property value. (defaults to: None) """ return self._values['duration'] @duration.setter def duration(self, value): """The duration property. Args: value (string). the property value. """ self._values['duration'] = value @property def response_code(self): """The response_code property. Returns: (string). the property value. (defaults to: None) """ return self._values['responseCode'] @response_code.setter def response_code(self, value): """The response_code property. Args: value (string). the property value. """ self._values['responseCode'] = value @property def success(self): """The success property. Returns: (bool). the property value. (defaults to: None) """ return self._values['success'] @success.setter def success(self, value): """The success property. Args: value (bool). the property value. """ self._values['success'] = value @property def http_method(self): """The http_method property. Returns: (string). the property value. (defaults to: None) """ if 'httpMethod' in self._values: return self._values['httpMethod'] return self._defaults['httpMethod'] @http_method.setter def http_method(self, value): """The http_method property. Args: value (string). the property value. """ if value == self._defaults['httpMethod'] and 'httpMethod' in self._values: del self._values['httpMethod'] else: self._values['httpMethod'] = value @property def url(self): """The url property. Returns: (string). the property value. (defaults to: None) """ if 'url' in self._values: return self._values['url'] return self._defaults['url'] @url.setter def url(self, value): """The url property. Args: value (string). the property value. """ if value == self._defaults['url'] and 'url' in self._values: del self._values['url'] else: self._values['url'] = value @property def properties(self): """The properties property. Returns: (hash). the property value. (defaults to: {}) """ if 'properties' in self._values: return self._values['properties'] self._values['properties'] = copy.deepcopy(self._defaults['properties']) return self._values['properties'] @properties.setter def properties(self, value): """The properties property. Args: value (hash). the property value. """ if value == self._defaults['properties'] and 'properties' in self._values: del self._values['properties'] else: self._values['properties'] = value @property def measurements(self): """The measurements property. Returns: (hash). the property value. (defaults to: {}) """ if 'measurements' in self._values: return self._values['measurements'] self._values['measurements'] = copy.deepcopy(self._defaults['measurements']) return self._values['measurements'] @measurements.setter def measurements(self, value): """The measurements property. Args: value (hash). the property value. """ if value == self._defaults['measurements'] and 'measurements' in self._values: del self._values['measurements'] else: self._values['measurements'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/Session.py0000644000076600000240000000566313143420775027565 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class Session(object): """Data contract class for type Session. """ _defaults = collections.OrderedDict([ ('ai.session.id', None), ('ai.session.isFirst', None), ('ai.session.isNew', None) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { } self._initialize() @property def id(self): """The id property. Returns: (string). the property value. (defaults to: None) """ if 'ai.session.id' in self._values: return self._values['ai.session.id'] return self._defaults['ai.session.id'] @id.setter def id(self, value): """The id property. Args: value (string). the property value. """ if value == self._defaults['ai.session.id'] and 'ai.session.id' in self._values: del self._values['ai.session.id'] else: self._values['ai.session.id'] = value @property def is_first(self): """The is_first property. Returns: (string). the property value. (defaults to: None) """ if 'ai.session.isFirst' in self._values: return self._values['ai.session.isFirst'] return self._defaults['ai.session.isFirst'] @is_first.setter def is_first(self, value): """The is_first property. Args: value (string). the property value. """ if value == self._defaults['ai.session.isFirst'] and 'ai.session.isFirst' in self._values: del self._values['ai.session.isFirst'] else: self._values['ai.session.isFirst'] = value @property def is_new(self): """The is_new property. Returns: (string). the property value. (defaults to: None) """ if 'ai.session.isNew' in self._values: return self._values['ai.session.isNew'] return self._defaults['ai.session.isNew'] @is_new.setter def is_new(self, value): """The is_new property. Args: value (string). the property value. """ if value == self._defaults['ai.session.isNew'] and 'ai.session.isNew' in self._values: del self._values['ai.session.isNew'] else: self._values['ai.session.isNew'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/SeverityLevel.py0000644000076600000240000000054313143420775030734 0ustar alexbstaff00000000000000class SeverityLevel(object): """Data contract class for type SeverityLevel.""" # Enumeration value verbose verbose = 0 # Enumeration value information information = 1 # Enumeration value warning warning = 2 # Enumeration value error error = 3 # Enumeration value critical critical = 4 applicationinsights-0.11.0/applicationinsights/channel/contracts/StackFrame.py0000644000076600000240000000724513143420775030160 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class StackFrame(object): """Data contract class for type StackFrame. """ _defaults = collections.OrderedDict([ ('level', None), ('method', None), ('assembly', None), ('fileName', None), ('line', None) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { 'level': None, 'method': None, } self._initialize() @property def level(self): """The level property. Returns: (int). the property value. (defaults to: None) """ return self._values['level'] @level.setter def level(self, value): """The level property. Args: value (int). the property value. """ self._values['level'] = value @property def method(self): """The method property. Returns: (string). the property value. (defaults to: None) """ return self._values['method'] @method.setter def method(self, value): """The method property. Args: value (string). the property value. """ self._values['method'] = value @property def assembly(self): """The assembly property. Returns: (string). the property value. (defaults to: None) """ if 'assembly' in self._values: return self._values['assembly'] return self._defaults['assembly'] @assembly.setter def assembly(self, value): """The assembly property. Args: value (string). the property value. """ if value == self._defaults['assembly'] and 'assembly' in self._values: del self._values['assembly'] else: self._values['assembly'] = value @property def file_name(self): """The file_name property. Returns: (string). the property value. (defaults to: None) """ if 'fileName' in self._values: return self._values['fileName'] return self._defaults['fileName'] @file_name.setter def file_name(self, value): """The file_name property. Args: value (string). the property value. """ if value == self._defaults['fileName'] and 'fileName' in self._values: del self._values['fileName'] else: self._values['fileName'] = value @property def line(self): """The line property. Returns: (int). the property value. (defaults to: None) """ if 'line' in self._values: return self._values['line'] return self._defaults['line'] @line.setter def line(self, value): """The line property. Args: value (int). the property value. """ if value == self._defaults['line'] and 'line' in self._values: del self._values['line'] else: self._values['line'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/User.py0000644000076600000240000000754613143420775027062 0ustar alexbstaff00000000000000import collections import copy from .Utils import _write_complex_object class User(object): """Data contract class for type User. """ _defaults = collections.OrderedDict([ ('ai.user.accountAcquisitionDate', None), ('ai.user.accountId', None), ('ai.user.userAgent', None), ('ai.user.id', None) ]) def __init__(self): """Initializes a new instance of the class. """ self._values = { } self._initialize() @property def account_acquisition_date(self): """The account_acquisition_date property. Returns: (string). the property value. (defaults to: None) """ if 'ai.user.accountAcquisitionDate' in self._values: return self._values['ai.user.accountAcquisitionDate'] return self._defaults['ai.user.accountAcquisitionDate'] @account_acquisition_date.setter def account_acquisition_date(self, value): """The account_acquisition_date property. Args: value (string). the property value. """ if value == self._defaults['ai.user.accountAcquisitionDate'] and 'ai.user.accountAcquisitionDate' in self._values: del self._values['ai.user.accountAcquisitionDate'] else: self._values['ai.user.accountAcquisitionDate'] = value @property def account_id(self): """The account_id property. Returns: (string). the property value. (defaults to: None) """ if 'ai.user.accountId' in self._values: return self._values['ai.user.accountId'] return self._defaults['ai.user.accountId'] @account_id.setter def account_id(self, value): """The account_id property. Args: value (string). the property value. """ if value == self._defaults['ai.user.accountId'] and 'ai.user.accountId' in self._values: del self._values['ai.user.accountId'] else: self._values['ai.user.accountId'] = value @property def user_agent(self): """The user_agent property. Returns: (string). the property value. (defaults to: None) """ if 'ai.user.userAgent' in self._values: return self._values['ai.user.userAgent'] return self._defaults['ai.user.userAgent'] @user_agent.setter def user_agent(self, value): """The user_agent property. Args: value (string). the property value. """ if value == self._defaults['ai.user.userAgent'] and 'ai.user.userAgent' in self._values: del self._values['ai.user.userAgent'] else: self._values['ai.user.userAgent'] = value @property def id(self): """The id property. Returns: (string). the property value. (defaults to: None) """ if 'ai.user.id' in self._values: return self._values['ai.user.id'] return self._defaults['ai.user.id'] @id.setter def id(self, value): """The id property. Args: value (string). the property value. """ if value == self._defaults['ai.user.id'] and 'ai.user.id' in self._values: del self._values['ai.user.id'] else: self._values['ai.user.id'] = value def _initialize(self): """Initializes the current instance of the object. """ pass def write(self): """Writes the contents of this object and returns the content as a dict object. Returns: (dict). the object that represents the same data as the current instance. """ return _write_complex_object(self._defaults, self._values) applicationinsights-0.11.0/applicationinsights/channel/contracts/Utils.py0000644000076600000240000000302713143420775027232 0ustar alexbstaff00000000000000import collections def _write_complex_object(defaults, values): output = collections.OrderedDict() for key in defaults.keys(): default = defaults[key] if key in values: value = values[key] if value == None: value = default elif default: value = default else: continue if isinstance(value, list): value_copy = [] for item in value: if hasattr(item, 'write') and callable(getattr(item, 'write')): value_copy.append(item.write()) else: value_copy.append(item) if len(value_copy) > 0: output[key] = value_copy elif isinstance(value, dict): value_copy = collections.OrderedDict() keys = sorted(value.keys()) for item_key in keys: item_value = value[item_key] if hasattr(item_value, 'write') and callable(getattr(item_value, 'write')): value_copy[item_key] = item_value.write() else: value_copy[item_key] = item_value if len(value_copy) > 0: output[key] = value_copy elif hasattr(value, 'write') and callable(getattr(value, 'write')): value_copy = value.write() if len(value_copy) > 0: output[key] = value_copy else: value_copy = value output[key] = value_copy return outputapplicationinsights-0.11.0/applicationinsights/channel/NullSender.py0000644000076600000240000000057013143421424026175 0ustar alexbstaff00000000000000from .SenderBase import SenderBase class NullSender(SenderBase): """A sender class that does not send data. Useful for debug mode, when telemetry may not be desired, with no changes to the object model. """ def __init__(self, *args, **kwargs): super(NullSender, self).__init__("nil-endpoint", *args, **kwargs) def send(self, data): pass applicationinsights-0.11.0/applicationinsights/channel/QueueBase.py0000644000076600000240000000573313143420775026017 0ustar alexbstaff00000000000000try: # Python 2.x from Queue import Queue, Empty except ImportError: # Python 3.x from queue import Queue, Empty class QueueBase(object): """The base class for all types of queues for use in conjunction with an implementation of :class:`SenderBase`. The queue will notify the sender that it needs to pick up items when it reaches :func:`max_queue_length`, or when the consumer calls :func:`flush`. """ def __init__(self, sender): """Initializes a new instance of the class. Args: sender (:class:`SenderBase`) the sender object that will be used in conjunction with this queue. """ self._queue = Queue() self._max_queue_length = 500 self._sender = sender if sender: self._sender.queue = self @property def max_queue_length(self): """The maximum number of items that will be held by the queue before the queue will call the :func:`flush` method. Args: value (int). the maximum queue length. The minimum allowed value is 1. Returns: int. the maximum queue size. (defaults to: 500) """ return self._max_queue_length @max_queue_length.setter def max_queue_length(self, value): """The maximum number of items that will be held by the queue before the queue will call the :func:`flush` method. Args: value (int): the maximum queue length. The minimum allowed value is 1. Returns: int. the maximum queue size. (defaults to: 500) """ if value < 1: value = 1 self._max_queue_length = value @property def sender(self): """The sender that is associated with this queue that this queue will use to send data to the service. Returns: :class:`SenderBase`. the sender object. """ return self._sender def put(self, item): """Adds the passed in item object to the queue and calls :func:`flush` if the size of the queue is larger than :func:`max_queue_length`. This method does nothing if the passed in item is None. Args: item (:class:`contracts.Envelope`) item the telemetry envelope object to send to the service. """ if not item: return self._queue.put(item) if self._queue.qsize() >= self._max_queue_length: self.flush() def get(self): """Gets a single item from the queue and returns it. If the queue is empty, this method will return None. Returns: :class:`contracts.Envelope`. a telemetry envelope object or None if the queue is empty. """ try: return self._queue.get_nowait() except Empty: return None def flush(self): """Flushes the current queue by notifying the {#sender}. This method needs to be overridden by a concrete implementations of the queue class. """ passapplicationinsights-0.11.0/applicationinsights/channel/SenderBase.py0000644000076600000240000001157713143421424026146 0ustar alexbstaff00000000000000import json try: # Python 2.x import urllib2 as HTTPClient from urllib2 import HTTPError except ImportError: # Python 3.x import urllib.request as HTTPClient from urllib.error import HTTPError class SenderBase(object): """The base class for all types of senders for use in conjunction with an implementation of :class:`QueueBase`. The queue will notify the sender that it needs to pick up items. The concrete sender implementation will listen to these notifications and will pull items from the queue getting at most :func:`send_buffer_size` items. It will then call :func:`send` using the list of items pulled from the queue. """ def __init__(self, service_endpoint_uri): """Initializes a new instance of the class. Args: service_endpoint_uri (str) the address of the service to send telemetry data to. """ self._service_endpoint_uri = service_endpoint_uri self._queue = None self._send_buffer_size = 100 self._timeout = 10 @property def service_endpoint_uri(self): """The HTTP or HTTPS endpoint that this sender will send data to. Args: value (str). the service endpoint URI. Returns: str. the service endpoint URI. """ return self._service_endpoint_uri @service_endpoint_uri.setter def service_endpoint_uri(self, value): """The service endpoint URI where this sender will send data to. Args: value (str). the service endpoint URI. Returns: str. the service endpoint URI. """ self._service_endpoint_uri = value @property def queue(self): """The queue that this sender is draining. While :class:`SenderBase` doesn't implement any means of doing so, derivations of this class do. Args: value (:class:`QueueBase`). the queue instance that this sender is draining. Returns: :class:`QueueBase`. the queue instance that this sender is draining. """ return self._queue @property def send_timeout(self): """Time in seconds that the sender should wait before giving up.""" return self._timeout @send_timeout.setter def send_timeout(self, seconds): """Configures the timeout in seconds the sender waits for a response for the server. Args: seconds(float). Timeout in seconds. """ self._send_buffer_size = seconds @queue.setter def queue(self, value): """The queue that this sender is draining. While :class:`SenderBase` doesn't implement any means of doing so, derivations of this class do. Args: value (:class:`QueueBase`). the queue instance that this sender is draining. Returns: :class:`QueueBase`. the queue instance that this sender is draining. """ self._queue = value @property def send_buffer_size(self): """The buffer size for a single batch of telemetry. This is the maximum number of items in a single service request that this sender is going to send. Args: value (int). the maximum number of items in a telemetry batch. Returns: int. the maximum number of items in a telemetry batch. """ return self._send_buffer_size @send_buffer_size.setter def send_buffer_size(self, value): """The buffer size for a single batch of telemetry. This is the maximum number of items in a single service request that this sender is going to send. Args: value (int). the maximum number of items in a telemetry batch. Returns: int. the maximum number of items in a telemetry batch. """ if value < 1: value = 1 self._send_buffer_size = value def send(self, data_to_send): """ Immediately sends the data passed in to :func:`service_endpoint_uri`. If the service request fails, the passed in items are pushed back to the :func:`queue`. Args: data_to_send (Array): an array of :class:`contracts.Envelope` objects to send to the service. """ request_payload = json.dumps([ a.write() for a in data_to_send ]) request = HTTPClient.Request(self._service_endpoint_uri, bytearray(request_payload, 'utf-8'), { 'Accept': 'application/json', 'Content-Type' : 'application/json; charset=utf-8' }) try: response = HTTPClient.urlopen(request, timeout=self._timeout) status_code = response.getcode() if 200 <= status_code < 300: return except HTTPError as e: if e.getcode() == 400: return except Exception as e: pass # Add our unsent data back on to the queue for data in data_to_send: self._queue.put(data) applicationinsights-0.11.0/applicationinsights/channel/SynchronousQueue.py0000644000076600000240000000247013143420775027472 0ustar alexbstaff00000000000000from .QueueBase import QueueBase class SynchronousQueue(QueueBase): """A synchronous queue for use in conjunction with the :class:`SynchronousSender`. The queue will call :func:`send` on :func:`sender` when it reaches :func:`max_queue_length`, or when the consumer calls :func:`flush`. .. code:: python from application_insights.channel import SynchronousQueue queue = SynchronousQueue(None) queue.max_queue_length = 1 queue.put(1) """ def __init__(self, sender): """Initializes a new instance of the class. Args: sender (:class:`SenderBase`) the sender object that will be used in conjunction with this queue. """ QueueBase.__init__(self, sender) def flush(self): """Flushes the current queue by by calling :func:`sender`'s :func:`send` method. """ local_sender = self.sender if not local_sender: return while True: # get at most send_buffer_size items and send them data = [] while len(data) < local_sender.send_buffer_size: item = self.get() if not item: break data.append(item) if len(data) == 0: break local_sender.send(data) applicationinsights-0.11.0/applicationinsights/channel/SynchronousSender.py0000644000076600000240000000111213143420775027616 0ustar alexbstaff00000000000000from .SenderBase import SenderBase class SynchronousSender(SenderBase): """A synchronous sender that works in conjunction with the :class:`SynchronousQueue`. The queue will call :func:`send` on the current instance with the data to send. """ def __init__(self, service_endpoint_uri='https://dc.services.visualstudio.com/v2/track'): """Initializes a new instance of the class. Args: sender (String) service_endpoint_uri the address of the service to send telemetry data to. """ SenderBase.__init__(self, service_endpoint_uri)applicationinsights-0.11.0/applicationinsights/channel/TelemetryChannel.py0000644000076600000240000001110213145103457027363 0ustar alexbstaff00000000000000import datetime import sys from .SynchronousQueue import SynchronousQueue from .SynchronousSender import SynchronousSender from .TelemetryContext import TelemetryContext from applicationinsights.channel import contracts platform_moniker = 'py2' if sys.version_info >= (3, 0): platform_moniker = 'py3' # set up internal context internal_context = contracts.Internal() internal_context.sdk_version = platform_moniker + ':0.11.0' class TelemetryChannel(object): """The telemetry channel is responsible for constructing a :class:`contracts.Envelope` object from the passed in data and specified telemetry context. .. code:: python from application_insights.channel import TelemetryChannel, contracts channel = TelemetryChannel() event = contracts.EventData() event.name = 'My event' channel.write(event) """ def __init__(self, context=None, queue=None): """Initializes a new instance of the class. Args: context (:class:`TelemetryContext') the telemetry context to use when sending telemetry data.\n queue (:class:`QueueBase`) the queue to enqueue the resulting :class:`contracts.Envelope` to. """ self._context = context or TelemetryContext() self._queue = queue or SynchronousQueue(SynchronousSender()) @property def context(self): """The context associated with this channel. All :class:`contracts.Envelope` objects created by this channel will use this value if it's present or if none is specified as part of the :func:`write` call. Returns: (:class:`TelemetryContext`). the context instance (defaults to: TelemetryContext()) """ return self._context @property def queue(self): """The queue associated with this channel. All :class:`contracts.Envelope` objects created by this channel will be pushed to this queue. Returns: (:class:`QueueBase`). the queue instance (defaults to: SynchronousQueue()) """ return self._queue @property def sender(self): """The sender associated with this channel. This instance will be used to transmit telemetry to the service. Returns: (:class:`SenderBase`). the sender instance (defaults to: SynchronousSender()) """ return self._queue.sender def flush(self): """Flushes the enqueued data by calling :func:`flush` on :func:`queue`. """ self._queue.flush() def write(self, data, context=None): """Enqueues the passed in data to the :func:`queue`. If the caller specifies a context as well, it will take precedence over the instance in :func:`context`. Args: data (object). data the telemetry data to send. This will be wrapped in an :class:`contracts.Envelope` before being enqueued to the :func:`queue`. context (:class:`TelemetryContext`). context the override context to use when constructing the :class:`contracts.Envelope`. """ local_context = context or self._context if not local_context: raise Exception('Context was required but not provided') if not data: raise Exception('Data was required but not provided') envelope = contracts.Envelope() envelope.name = data.ENVELOPE_TYPE_NAME envelope.time = datetime.datetime.utcnow().isoformat() + 'Z' envelope.ikey = local_context.instrumentation_key tags = envelope.tags for key, value in self._write_tags(local_context): tags[key] = value envelope.data = contracts.Data() envelope.data.base_type = data.DATA_TYPE_NAME if hasattr(data, 'properties') and local_context.properties: properties = data.properties if not properties: properties = {} data.properties = properties for key in local_context.properties: if key not in properties: properties[key] = local_context.properties[key] envelope.data.base_data = data self._queue.put(envelope) def _write_tags(self, context): for item in [ internal_context, context.device, context.application, context.user, context.session, context.location, context.operation ]: if not item: continue for pair in item.write().items(): yield pair applicationinsights-0.11.0/applicationinsights/channel/TelemetryContext.py0000644000076600000240000000350513143420775027452 0ustar alexbstaff00000000000000import platform import locale from applicationinsights.channel import contracts # save off whatever is currently there existing_device_initialize = contracts.Device._initialize def device_initialize(self): """ The device initializer used to assign special properties to all device context objects""" existing_device_initialize(self) self.type = 'Other' self.id = platform.node() self.os_version = platform.version() self.locale = locale.getdefaultlocale()[0] # assign the device context initializer contracts.Device._initialize = device_initialize class TelemetryContext(object): """Represents the context for sending telemetry to the Application Insights service. .. code:: python context = TelemetryContext() context.instrumentation_key = '' context.application.id = 'My application' context.application.ver = '1.2.3' context.device.id = 'My current device' context.device.oem_name = 'Asus' context.device.model = 'X31A' context.device.type = "Other" context.user.id = 'santa@northpole.net' track_trace('My trace with context') """ def __init__(self): """Initializes a new instance of the class. """ self.instrumentation_key = None self.device = contracts.Device() self.application = contracts.Application() self.user = contracts.User() self.session = contracts.Session() self.operation = contracts.Operation() self.location = contracts.Location() self._properties = {} @property def properties(self): """The property context. This contains free-form properties that you can add to your telemetry. Returns: (dict). the context object. """ return self._properties applicationinsights-0.11.0/applicationinsights/django/0000755000076600000240000000000013145103565023405 5ustar alexbstaff00000000000000applicationinsights-0.11.0/applicationinsights/django/__init__.py0000644000076600000240000000066113143421424025514 0ustar alexbstaff00000000000000from .middleware import ApplicationInsightsMiddleware from .logging import LoggingHandler from . import common __all__ = ['ApplicationInsightsMiddleware', 'LoggingHandler', 'create_client'] def create_client(): """Returns an :class:`applicationinsights.TelemetryClient` instance using the instrumentation key and other settings found in the current Django project's `settings.py` file.""" return common.create_client() applicationinsights-0.11.0/applicationinsights/django/common.py0000644000076600000240000000570013143421424025244 0ustar alexbstaff00000000000000import collections from django.conf import settings import applicationinsights ApplicationInsightsSettings = collections.namedtuple("ApplicationInsightsSettings", [ "ikey", "channel_settings", "use_view_name", "record_view_arguments", "log_exceptions"]) ApplicationInsightsChannelSettings = collections.namedtuple("ApplicationInsightsChannelSettings", [ "send_interval", "send_time", "endpoint"]) def load_settings(): if hasattr(settings, "APPLICATION_INSIGHTS"): config = settings.APPLICATION_INSIGHTS elif hasattr(settings, "APPLICATIONINSIGHTS"): config = settings.APPLICATIONINSIGHTS else: config = {} if not isinstance(config, dict): config = {} return ApplicationInsightsSettings( ikey=config.get("ikey"), use_view_name=config.get("use_view_name", False), record_view_arguments=config.get("record_view_arguments", False), log_exceptions=config.get("log_exceptions", True), channel_settings=ApplicationInsightsChannelSettings( endpoint=config.get("endpoint"), send_interval=config.get("send_interval"), send_time=config.get("send_time"))) saved_clients = {} saved_channels = {} def create_client(aisettings=None): global saved_clients, saved_channels if aisettings is None: aisettings = load_settings() if aisettings in saved_clients: return saved_clients[aisettings] channel_settings = aisettings.channel_settings if channel_settings in saved_channels: channel = saved_channels[channel_settings] else: if channel_settings.endpoint is not None: sender = applicationinsights.channel.AsynchronousSender(service_endpoint_uri=channel_settings.endpoint) else: sender = applicationinsights.channel.AsynchronousSender() if channel_settings.send_time is not None: sender.send_time = channel_settings.send_time if channel_settings.send_interval is not None: sender.send_interval = channel_settings.send_interval queue = applicationinsights.channel.AsynchronousQueue(sender) channel = applicationinsights.channel.TelemetryChannel(None, queue) saved_channels[channel_settings] = channel ikey = aisettings.ikey if ikey is None: return dummy_client("No ikey specified") client = applicationinsights.TelemetryClient(aisettings.ikey, channel) saved_clients[aisettings] = client return client def dummy_client(reason): """Creates a dummy channel so even if we're not logging telemetry, we can still send along the real object to things that depend on it to exist""" sender = applicationinsights.channel.NullSender() queue = applicationinsights.channel.SynchronousQueue(sender) channel = applicationinsights.channel.TelemetryChannel(None, queue) return applicationinsights.TelemetryClient("00000000-0000-0000-0000-000000000000", channel) applicationinsights-0.11.0/applicationinsights/django/logging.py0000644000076600000240000000327713143421424025411 0ustar alexbstaff00000000000000 from . import common from applicationinsights import logging import sys class LoggingHandler(logging.LoggingHandler): """This class is a LoggingHandler that uses the same settings as the Django middleware to configure the telemetry client. This can be referenced from LOGGING in your Django settings.py file. As an example, this code would send all Django log messages--WARNING and up--to Application Insights: .. code:: python LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { # The application insights handler is here 'appinsights': { 'class': 'applicationinsights.django.LoggingHandler', 'level': 'WARNING' } }, 'loggers': { 'django': { 'handlers': ['appinsights'], 'level': 'WARNING', 'propagate': True, } } } # You will need this anyway if you're using the middleware. # See the middleware documentation for more information on configuring # this setting: APPLICATION_INSIGHTS = { 'ikey': '00000000-0000-0000-0000-000000000000' } """ def __init__(self, *args, **kwargs): client = common.create_client() new_kwargs = {} new_kwargs.update(kwargs) new_kwargs['telemetry_channel'] = client.channel super(LoggingHandler, self).__init__(client.context.instrumentation_key, *args, **new_kwargs) applicationinsights-0.11.0/applicationinsights/django/middleware.py0000644000076600000240000002463513143421424026101 0ustar alexbstaff00000000000000 import datetime import inspect import sys import time import uuid from django.http import Http404 import applicationinsights from applicationinsights.channel import contracts from . import common # Pick a function to measure time; starting with 3.3, time.monotonic is available. if sys.version_info >= (3, 3): TIME_FUNC = time.monotonic else: TIME_FUNC = time.time class ApplicationInsightsMiddleware(object): """This class is a Django middleware that automatically enables request and exception telemetry. Django versions 1.7 and newer are supported. To enable, add this class to your settings.py file in MIDDLEWARE_CLASSES (pre-1.10) or MIDDLEWARE (1.10 and newer): .. code:: python # If on Django < 1.10 MIDDLEWARE_CLASSES = [ # ... or whatever is below for you ... 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # ... or whatever is above for you ... 'applicationinsights.django.ApplicationInsightsMiddleware', # Add this middleware to the end ] # If on Django >= 1.10 MIDDLEWARE = [ # ... or whatever is below for you ... 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # ... or whatever is above for you ... 'applicationinsights.django.ApplicationInsightsMiddleware', # Add this middleware to the end ] And then, add the following to your settings.py file: .. code:: python APPLICATION_INSIGHTS = { # (required) Your Application Insights instrumentation key 'ikey': "00000000-0000-0000-0000-000000000000", # (optional) By default, request names are logged as the request method # and relative path of the URL. To log the fully-qualified view names # instead, set this to True. Defaults to False. 'use_view_name': True, # (optional) To log arguments passed into the views as custom properties, # set this to True. Defaults to False. 'record_view_arguments': True, # (optional) Exceptions are logged by default, to disable, set this to False. 'log_exceptions': False, # (optional) Events are submitted to Application Insights asynchronously. # send_interval specifies how often the queue is checked for items to submit. # send_time specifies how long the sender waits for new input before recycling # the background thread. 'send_interval': 1.0, # Check every second 'send_time': 3.0, # Wait up to 3 seconds for an event # (optional, uncommon) If you must send to an endpoint other than the # default endpoint, specify it here: 'endpoint': "https://dc.services.visualstudio.com/v2/track", } Once these are in place, each request will have an `appinsights` object placed on it. This object will have the following properties: * `client`: This is an instance of the :class:`applicationinsights.TelemetryClient` type, which will submit telemetry to the same instrumentation key, and will parent each telemetry item to the current request. * `request`: This is the :class:`applicationinsights.channel.contracts.RequestData` instance for the current request. You can modify properties on this object during the handling of the current request. It will be submitted when the request has finished. * `context`: This is the :class:`applicationinsights.channel.TelemetryContext` object for the current ApplicationInsights sender. These properties will be present even when `DEBUG` is `True`, but it may not submit telemetry unless `debug_ikey` is set in `APPLICATION_INSIGHTS`, above. """ def __init__(self, get_response=None): self.get_response = get_response # Get configuration self._settings = common.load_settings() self._client = common.create_client(self._settings) # Pre-1.10 handler def process_request(self, request): # Populate context object onto request addon = RequestAddon(self._client) data = addon.request context = addon.context request.appinsights = addon # Basic request properties data.start_time = datetime.datetime.utcnow().isoformat() + "Z" data.http_method = request.method data.url = request.build_absolute_uri() data.name = "%s %s" % (request.method, request.path) context.operation.name = data.name context.operation.id = data.id context.location.ip = request.META.get('REMOTE_ADDR', '') context.user.user_agent = request.META.get('HTTP_USER_AGENT', '') # User if request.user is not None and not request.user.is_anonymous and request.user.is_authenticated: context.user.account_id = request.user.get_short_name() # Run and time the request addon.start_stopwatch() return None # Pre-1.10 handler def process_response(self, request, response): addon = request.appinsights duration = addon.measure_duration() data = addon.request context = addon.context # Fill in data from the response data.duration = addon.measure_duration() data.response_code = response.status_code data.success = response.status_code < 400 or response.status_code == 401 # Submit and return self._client.channel.write(data, context) return response # 1.10 and up... def __call__(self, request): self.process_request(request) response = self.get_response(request) self.process_response(request, response) return response def process_view(self, request, view_func, view_args, view_kwargs): if not hasattr(request, "appinsights"): return None data = request.appinsights.request context = request.appinsights.context # Operation name is the method + url by default (set in __call__), # If use_view_name is set, then we'll look up the name of the view. if self._settings.use_view_name: mod = inspect.getmodule(view_func) name = view_func.__name__ if mod: opname = "%s %s.%s" % (data.http_method, mod.__name__, name) else: opname = "%s %s" % (data.http_method, name) data.name = opname context.operation.name = opname # Populate the properties with view arguments if self._settings.record_view_arguments: for i, arg in enumerate(view_args): data.properties['view_arg_' + str(i)] = arg_to_str(arg) for k, v in view_kwargs.items(): data.properties['view_arg_' + k] = arg_to_str(v) return None def process_exception(self, request, exception): if not self._settings.log_exceptions: return None if type(exception) is Http404: return None _, _, tb = sys.exc_info() if tb is None or exception is None: # No actual traceback or exception info, don't bother logging. return None client = applicationinsights.TelemetryClient(self._client.context.instrumentation_key, self._client.channel) if hasattr(request, 'appinsights'): client.context.operation.parent_id = request.appinsights.request.id client.track_exception(type(exception), exception, tb) return None def process_template_response(self, request, response): if hasattr(request, 'appinsights') and hasattr(response, 'template_name'): data = request.appinsights.request data.properties['template_name'] = response.template_name return None class RequestAddon(object): def __init__(self, client): self._baseclient = client self._client = None self.request = contracts.RequestData() self.request.id = str(uuid.uuid4()) self.context = applicationinsights.channel.TelemetryContext() self.context.instrumentation_key = client.context.instrumentation_key self.context.operation.id = self.request.id self._process_start_time = None @property def client(self): if self._client is None: # Create a client that submits telemetry parented to the request. self._client = applicationinsights.TelemetryClient(self.context.instrumentation_key, self._baseclient.channel) self._client.context.operation.parent_id = self.context.operation.id return self._client def start_stopwatch(self): self._process_start_time = TIME_FUNC() def measure_duration(self): end_time = TIME_FUNC() return ms_to_duration(int((end_time - self._process_start_time) * 1000)) def ms_to_duration(n): duration_parts = [] for multiplier in [1000, 60, 60, 24]: duration_parts.append(n % multiplier) n //= multiplier duration_parts.reverse() duration = "%02d:%02d:%02d.%03d" % tuple(duration_parts) if n: duration = "%d.%s" % (n, duration) return duration def arg_to_str_3(arg): if isinstance(arg, str): return arg if isinstance(arg, int): return str(arg) return repr(arg) def arg_to_str_2(arg): if isinstance(arg, str) or isinstance(arg, unicode): return arg if isinstance(arg, int): return str(arg) return repr(arg) if sys.version_info < (3, 0): arg_to_str = arg_to_str_2 else: arg_to_str = arg_to_str_3 applicationinsights-0.11.0/applicationinsights/exceptions/0000755000076600000240000000000013145103565024324 5ustar alexbstaff00000000000000applicationinsights-0.11.0/applicationinsights/exceptions/__init__.py0000644000076600000240000000003213143420775026433 0ustar alexbstaff00000000000000from .enable import enableapplicationinsights-0.11.0/applicationinsights/exceptions/enable.py0000644000076600000240000000337513143420775026137 0ustar alexbstaff00000000000000import sys from applicationinsights import TelemetryClient, channel original_excepthook = None telemetry_channel = None enabled_instrumentation_keys = [] def enable(instrumentation_key, *args, **kwargs): """Enables the automatic collection of unhandled exceptions. Captured exceptions will be sent to the Application Insights service before being re-thrown. Multiple calls to this function with different instrumentation keys result in multiple instances being submitted, one for each key. .. code:: python from applicationinsights.exceptions import enable # set up exception capture enable('') # raise an exception (this will be sent to the Application Insights service as an exception telemetry object) raise Exception('Boom!') Args: instrumentation_key (str). the instrumentation key to use while sending telemetry to the service. """ if not instrumentation_key: raise Exception('Instrumentation key was required but not provided') global original_excepthook global telemetry_channel telemetry_channel = kwargs.get('telemetry_channel') if not original_excepthook: original_excepthook = sys.excepthook sys.excepthook = intercept_excepthook if instrumentation_key not in enabled_instrumentation_keys: enabled_instrumentation_keys.append(instrumentation_key) 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)applicationinsights-0.11.0/applicationinsights/logging/0000755000076600000240000000000013145103565023571 5ustar alexbstaff00000000000000applicationinsights-0.11.0/applicationinsights/logging/__init__.py0000644000076600000240000000011513143420775025702 0ustar alexbstaff00000000000000from .LoggingHandler import enable from .LoggingHandler import LoggingHandlerapplicationinsights-0.11.0/applicationinsights/logging/LoggingHandler.py0000644000076600000240000001053613143421424027027 0ustar alexbstaff00000000000000import logging import applicationinsights enabled_instrumentation_keys = {} def enable(instrumentation_key, *args, **kwargs): """Enables the Application Insights logging handler for the root logger for the supplied instrumentation key. Multiple calls to this function with different instrumentation keys result in multiple handler instances. .. code:: python import logging from applicationinsights.logging import enable # set up logging enable('') # log something (this will be sent to the Application Insights service as a trace) logging.info('This is a message') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively set up an async channel via enable('', telemetry_channel=...) Args: instrumentation_key (str). the instrumentation key to use while sending telemetry to the service. Returns: :class:`ApplicationInsightsHandler`. the newly created or existing handler. """ if not instrumentation_key: raise Exception('Instrumentation key was required but not provided') if instrumentation_key in enabled_instrumentation_keys: logging.getLogger().removeHandler(enabled_instrumentation_keys[instrumentation_key]) handler = LoggingHandler(instrumentation_key, *args, **kwargs) handler.setLevel(logging.INFO) enabled_instrumentation_keys[instrumentation_key] = handler logging.getLogger().addHandler(handler) return handler class LoggingHandler(logging.Handler): """This class represents an integration point between Python's logging framework and the Application Insights service. Logging records are sent to the service either as simple Trace telemetry or as Exception telemetry (in the case of exception information being available). .. code:: python import logging from applicationinsights.logging import ApplicationInsightsHandler # set up logging handler = ApplicationInsightsHandler('') logging.basicConfig(handlers=[ handler ], format='%(levelname)s: %(message)s', level=logging.DEBUG) # log something (this will be sent to the Application Insights service as a trace) logging.info('This is a message') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively flush manually via handler.flush() """ def __init__(self, instrumentation_key, *args, **kwargs): """ Initialize a new instance of the class. Args: instrumentation_key (str). the instrumentation key to use while sending telemetry to the service. """ if not instrumentation_key: raise Exception('Instrumentation key was required but not provided') telemetry_channel = kwargs.get('telemetry_channel') if 'telemetry_channel' in kwargs: del kwargs['telemetry_channel'] self.client = applicationinsights.TelemetryClient(instrumentation_key, telemetry_channel) super(LoggingHandler, self).__init__(*args, **kwargs) def flush(self): """Flushes the queued up telemetry to the service. """ self.client.flush() return super(LoggingHandler, self).flush() def emit(self, record): """Emit a record. If a formatter is specified, it is used to format the record. If exception information is present, an Exception telemetry object is sent instead of a Trace telemetry object. Args: record (:class:`logging.LogRecord`). the record to format and send. """ # the set of properties that will ride with the record properties = { 'process': record.processName, 'module': record.module, 'fileName': record.filename, 'lineNumber': record.lineno, 'level': record.levelname, } # if we have exec_info, we will use it as an exception if record.exc_info: self.client.track_exception(*record.exc_info, properties=properties) return # if we don't simply format the message and send the trace formatted_message = self.format(record) self.client.track_trace(formatted_message, properties=properties, severity=record.levelname) applicationinsights-0.11.0/applicationinsights/requests/0000755000076600000240000000000013145103565024016 5ustar alexbstaff00000000000000applicationinsights-0.11.0/applicationinsights/requests/__init__.py0000644000076600000240000000005513143420775026132 0ustar alexbstaff00000000000000from .WSGIApplication import WSGIApplication applicationinsights-0.11.0/applicationinsights/requests/WSGIApplication.py0000644000076600000240000000752613143420775027342 0ustar alexbstaff00000000000000import datetime import re import applicationinsights class WSGIApplication(object): """ This class represents a WSGI wrapper that enables request telemetry for existing WSGI applications. The request telemetry will be sent to Application Insights service using the supplied instrumentation key. .. code:: python from flask import Flask from applicationinsights.requests import WSGIApplication # instantiate the Flask application and wrap its WSGI application app = Flask(__name__) app.wsgi_app = WSGIApplication('', app.wsgi_app) # define a simple route @app.route('/') def hello_world(): return 'Hello World!' # run the application if __name__ == '__main__': app.run() """ def __init__(self, instrumentation_key, wsgi_application, *args, **kwargs): """ Initialize a new instance of the class. Args: instrumentation_key (str). the instrumentation key to use while sending telemetry to the service.\n wsgi_application (func). the WSGI application that we're wrapping. """ if not instrumentation_key: raise Exception('Instrumentation key was required but not provided') if not wsgi_application: raise Exception('WSGI application was required but not provided') telemetry_channel = kwargs.pop('telemetry_channel', None) if not telemetry_channel: sender = applicationinsights.channel.AsynchronousSender() queue = applicationinsights.channel.AsynchronousQueue(sender) telemetry_channel = applicationinsights.channel.TelemetryChannel(None, queue) self.client = applicationinsights.TelemetryClient(instrumentation_key, telemetry_channel) self._wsgi_application = wsgi_application def flush(self): """Flushes the queued up telemetry to the service. """ self.client.flush() def __call__(self, environ, start_response): """Callable implementation for WSGI middleware. Args: environ (dict). a dictionary containing all WSGI environment properties for this request.\n start_response (func). a function used to store the status, HTTP headers to be sent to the client and optional exception information. Returns: (obj). the response to send back to the client. """ start_time = datetime.datetime.utcnow() name = environ.get('PATH_INFO') or '/' closure = {'status': '200 OK'} def status_interceptor(status_string, headers_array, exc_info=None): closure['status'] = status_string start_response(status_string, headers_array, exc_info) for part in self._wsgi_application(environ, status_interceptor): yield part success = True response_match = re.match(r'\s*(?P\d+)', closure['status']) if response_match: response_code = response_match.group('code') if int(response_code) >= 400: success = False else: response_code = closure['status'] success = False http_method = environ.get('REQUEST_METHOD', 'GET') url = name query_string = environ.get('QUERY_STRING') if query_string: url += '?' + query_string scheme = environ.get('wsgi.url_scheme', 'http') host = environ.get('HTTP_HOST', environ.get('SERVER_NAME', 'unknown')) url = scheme + '://' + host + url end_time = datetime.datetime.utcnow() duration = int((end_time - start_time).total_seconds() * 1000) self.client.track_request(name, url, success, start_time.isoformat() + 'Z', duration, response_code, http_method) applicationinsights-0.11.0/applicationinsights/TelemetryClient.py0000644000076600000240000002466513143421424025636 0ustar alexbstaff00000000000000import datetime import traceback import sys import uuid from applicationinsights import channel NULL_CONSTANT_STRING = 'Null' class TelemetryClient(object): """The telemetry client used for sending all types of telemetry. It serves as the main entry point for interacting with the Application Insights service. """ def __init__(self, instrumentation_key, telemetry_channel=None): """Initializes a new instance of the class. Args: instrumentation_key (str). the instrumentation key to use for this telemetry client.\n telemetry_channel (:class:`channel.TelemetryChannel`). the optional telemetry channel to be used instead of constructing a default one. """ if instrumentation_key: if isinstance(instrumentation_key, channel.TelemetryChannel): telemetry_channel = instrumentation_key instrumentation_key = None else: raise Exception('Instrumentation key was required but not provided') self._context = channel.TelemetryContext() self._context.instrumentation_key = instrumentation_key self._channel = telemetry_channel or channel.TelemetryChannel() @property def context(self): """The context associated with this client. All data objects created by this client will be accompanied by this value. Returns: :class:`channel.TelemetryChannel`. the context instance. """ return self._context @property def channel(self): """The channel associated with this telemetry client. All data created by this client will be passed along with the :func:`context` object to :class:`channel.TelemetryChannel`'s :func:`write`. Returns: :class:`channel.TelemetryChannel`. the channel instance. """ return self._channel def flush(self): """Flushes data in the queue. Data in the queue will be sent either immediately irrespective of what sender is being used. """ self._channel.flush() def track_pageview(self, name, url, duration=0, properties=None, measurements=None): """Send information about the page viewed in the application (a web page for instance). Args: name (str). the name of the page that was viewed.\n url (str). the URL of the page that was viewed.\n duration (int). the duration of the page view in milliseconds. (defaults to: 0)\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\n measurements (dict). the set of custom measurements the client wants to attach to this data item. (defaults to: None) """ data = channel.contracts.PageViewData() data.name = name or NULL_CONSTANT_STRING data.url = url data.duration = duration if properties: data.properties = properties if measurements: data.measurements = measurements self._channel.write(data, self._context) def track_exception(self, type=None, value=None, tb=None, properties=None, measurements=None): """ Send information about a single exception that occurred in the application. Args: type (Type). the type of the exception that was thrown.\n value (:class:`Exception`). the exception that the client wants to send.\n tb (:class:`Traceback`). the traceback information as returned by :func:`sys.exc_info`.\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\n measurements (dict). the set of custom measurements the client wants to attach to this data item. (defaults to: None) """ if not type or not value or not tb: type, value, tb = sys.exc_info() if not type or not value or not tb: try: raise Exception(NULL_CONSTANT_STRING) except: type, value, tb = sys.exc_info() details = channel.contracts.ExceptionDetails() details.id = 1 details.outer_id = 0 details.type_name = type.__name__ details.message = str(value) details.has_full_stack = True counter = 0 for tb_frame_file, tb_frame_line, tb_frame_function, tb_frame_text in traceback.extract_tb(tb): frame = channel.contracts.StackFrame() frame.assembly = 'Unknown' frame.file_name = tb_frame_file frame.level = counter frame.line = tb_frame_line frame.method = tb_frame_function details.parsed_stack.append(frame) counter += 1 details.parsed_stack.reverse() data = channel.contracts.ExceptionData() data.handled_at = 'UserCode' data.exceptions.append(details) if properties: data.properties = properties if measurements: data.measurements = measurements self._channel.write(data, self._context) def track_event(self, name, properties=None, measurements=None): """ Send information about a single event that has occurred in the context of the application. Args: name (str). the data to associate to this event.\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\n measurements (dict). the set of custom measurements the client wants to attach to this data item. (defaults to: None) """ data = channel.contracts.EventData() data.name = name or NULL_CONSTANT_STRING if properties: data.properties = properties if measurements: data.measurements = measurements self._channel.write(data, self._context) def track_metric(self, name, value, type=None, count=None, min=None, max=None, std_dev=None, properties=None): """Send information about a single metric data point that was captured for the application. Args: name (str). the name of the metric that was captured.\n value (float). the value of the metric that was captured.\n type (:class:`channel.contracts.DataPointType`). the type of the metric. (defaults to: :func:`channel.contracts.DataPointType.aggregation`)\n count (int). the number of metrics that were aggregated into this data point. (defaults to: None)\n min (float). the minimum of all metrics collected that were aggregated into this data point. (defaults to: None)\n max (float). the maximum of all metrics collected that were aggregated into this data point. (defaults to: None)\n std_dev (float). the standard deviation of all metrics collected that were aggregated into this data point. (defaults to: None)\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None) """ dataPoint = channel.contracts.DataPoint() dataPoint.name = name or NULL_CONSTANT_STRING dataPoint.value = value or 0 dataPoint.kind = type or channel.contracts.DataPointType.aggregation dataPoint.count = count dataPoint.min = min dataPoint.max = max dataPoint.std_dev = std_dev data = channel.contracts.MetricData() data.metrics.append(dataPoint) if properties: data.properties = properties self._channel.write(data, self._context) def track_trace(self, name, properties=None, severity=None): """Sends a single trace statement. Args: name (str). the trace statement.\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\n severity (str). the severity level of this trace, one of DEBUG, INFO, WARNING, ERROR, CRITICAL """ data = channel.contracts.MessageData() data.message = name or NULL_CONSTANT_STRING if properties: data.properties = properties if severity is not None: data.severity_level = channel.contracts.MessageData.PYTHON_LOGGING_LEVELS.get(severity) self._channel.write(data, self._context) def track_request(self, name, url, success, start_time=None, duration=None, response_code=None, http_method=None, properties=None, measurements=None): """Sends a single request that was captured for the application. Args: name (str). the name for this request. All requests with the same name will be grouped together.\n url (str). the actual URL for this request (to show in individual request instances).\n success (bool). true if the request ended in success, false otherwise.\n start_time (str). the start time of the request. The value should look the same as the one returned by :func:`datetime.isoformat()` (defaults to: None)\n duration (int). the number of milliseconds that this request lasted. (defaults to: None)\n response_code (string). the response code that this request returned. (defaults to: None)\n http_method (string). the HTTP method that triggered this request. (defaults to: None)\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\n measurements (dict). the set of custom measurements the client wants to attach to this data item. (defaults to: None) """ data = channel.contracts.RequestData() data.id = str(uuid.uuid4()) data.name = name data.start_time = start_time or datetime.datetime.utcnow().isoformat() + 'Z' local_duration = duration or 0 duration_parts = [] for multiplier in [1000, 60, 60, 24]: duration_parts.append(local_duration % multiplier) local_duration //= multiplier duration_parts.reverse() data.duration = '%02d:%02d:%02d.%03d' % tuple(duration_parts) if local_duration: data.duration = '%d.%s' % (local_duration, data.duration) data.response_code = response_code or '200' data.success = success data.http_method = http_method or 'GET' data.url = url if properties: data.properties = properties if measurements: data.measurements = measurements self.channel.write(data, self._context) applicationinsights-0.11.0/applicationinsights.egg-info/0000755000076600000240000000000013145103565023635 5ustar alexbstaff00000000000000applicationinsights-0.11.0/applicationinsights.egg-info/dependency_links.txt0000644000076600000240000000000113145103565027703 0ustar alexbstaff00000000000000 applicationinsights-0.11.0/applicationinsights.egg-info/PKG-INFO0000644000076600000240000002172513145103565024741 0ustar alexbstaff00000000000000Metadata-Version: 1.1 Name: applicationinsights Version: 0.11.0 Summary: This project extends the Application Insights API surface to support Python. Home-page: https://github.com/Microsoft/AppInsights-Python Author: Microsoft Author-email: aiengdisc@microsoft.com License: MIT Download-URL: https://github.com/Microsoft/AppInsights-Python Description: Application Insights for Python =============================== This project extends the Application Insights API surface to support Python. `Application Insights `_ is a service that allows developers to keep their application available, performing and succeeding. This Python module will allow you to send telemetry of various kinds (event, trace, exception, etc.) to the Application Insights service where they can be visualized in the Azure Portal. Requirements ------------ Python 2.7 and Python 3.4 are currently supported by this module. For opening the project in Microsoft Visual Studio you will need `Python Tools for Visual Studio `_. Installation ------------ To install the latest release you can use `pip `_. :: $ pip install applicationinsights Usage ----- Once installed, you can send telemetry to Application Insights. Here are a few samples. **Note**: before you can send data to you will need an instrumentation key. Please see the `Getting an Application Insights Instrumentation Key `_ section for more information. **Sending a simple event telemetry item** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_event("Test event") tc.flush() **Sending an event telemetry item with custom properties and measurements** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_event('Test event', { 'foo': 'bar' }, { 'baz': 42 }) tc.flush() **Sending a trace telemetry item with custom properties** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_trace('Test trace', { 'foo': 'bar' }) tc.flush() **Sending a metric telemetry item** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_metric('My Metric', 42) tc.flush() **Sending an exception telemetry item with custom properties and measurements** .. code:: python import sys from applicationinsights import TelemetryClient tc = TelemetryClient('') try: raise Exception('blah') except: tc.track_exception() try: raise Exception("blah") except: tc.track_exception(*sys.exc_info(), properties={ 'foo': 'bar' }, measurements={ 'x': 42 }) tc.flush() **Configuring context for a telemetry client instance** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.context.application.id = 'My application' tc.context.application.ver = '1.2.3' tc.context.device.id = 'My current device' tc.context.device.oem_name = 'Asus' tc.context.device.model = 'X31A' tc.context.device.type = "Other" tc.context.user.id = 'santa@northpole.net' tc.track_trace('My trace with context') tc.flush() **Configuring channel related properties** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') # flush telemetry every 30 seconds (assuming we don't hit max_queue_item_count first) tc.channel.sender.send_interval_in_milliseconds = 30 * 1000 # flush telemetry if we have 10 or more telemetry items in our queue tc.channel.sender.max_queue_item_count = 10 **Basic logging configuration (first option)** .. code:: python import logging from applicationinsights.logging import enable # set up logging enable('') # log something (this will be sent to the Application Insights service as a trace) logging.info('This is a message') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively flush manually via handler.flush() **Basic logging configuration (second option)** .. code:: python import logging from applicationinsights.logging import LoggingHandler # set up logging handler = LoggingHandler('') logging.basicConfig(handlers=[ handler ], format='%(levelname)s: %(message)s', level=logging.DEBUG) # log something (this will be sent to the Application Insights service as a trace) logging.debug('This is a message') try: raise Exception('Some exception') except: # this will send an exception to the Application Insights service logging.exception('Code went boom!') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively flush manually via handler.flush() **Advanced logging configuration** .. code:: python import logging from applicationinsights.logging import LoggingHandler # set up logging handler = LoggingHandler('') handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s')) my_logger = logging.getLogger('simple_logger') my_logger.setLevel(logging.DEBUG) my_logger.addHandler(handler) # log something (this will be sent to the Application Insights service as a trace) my_logger.debug('This is a message') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively flush manually via handler.flush() **Logging unhandled exceptions** .. code:: python from applicationinsights.exceptions import enable # set up exception capture enable('') # raise an exception (this will be sent to the Application Insights service as an exception telemetry object) raise Exception('Boom!') **Logging requests** .. code:: python from flask import Flask from applicationinsights.requests import WSGIApplication # instantiate the Flask application and wrap its WSGI application app = Flask(__name__) app.wsgi_app = WSGIApplication('', app.wsgi_app) # define a simple route @app.route('/') def hello_world(): return 'Hello World!' # run the application if __name__ == '__main__': app.run() Keywords: analytics applicationinsights telemetry appinsights development Platform: UNKNOWN Classifier: Development Status :: 3 - Alpha Classifier: Intended Audience :: Developers Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Operating System :: OS Independent Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.4 applicationinsights-0.11.0/applicationinsights.egg-info/SOURCES.txt0000644000076600000240000001231613145103565025524 0ustar alexbstaff00000000000000DESCRIPTION.rst LICENSE.txt MANIFEST.in Microsoft.ApplicationInsights.pyproj Microsoft.ApplicationInsights.sln README.md setup.cfg setup.py applicationinsights/TelemetryClient.py applicationinsights/__init__.py applicationinsights.egg-info/PKG-INFO applicationinsights.egg-info/SOURCES.txt applicationinsights.egg-info/dependency_links.txt applicationinsights.egg-info/top_level.txt applicationinsights/channel/AsynchronousQueue.py applicationinsights/channel/AsynchronousSender.py applicationinsights/channel/NullSender.py applicationinsights/channel/QueueBase.py applicationinsights/channel/SenderBase.py applicationinsights/channel/SynchronousQueue.py applicationinsights/channel/SynchronousSender.py applicationinsights/channel/TelemetryChannel.py applicationinsights/channel/TelemetryContext.py applicationinsights/channel/__init__.py applicationinsights/channel/contracts/Application.py applicationinsights/channel/contracts/Data.py applicationinsights/channel/contracts/DataPoint.py applicationinsights/channel/contracts/DataPointType.py applicationinsights/channel/contracts/DependencyKind.py applicationinsights/channel/contracts/DependencySourceType.py applicationinsights/channel/contracts/Device.py applicationinsights/channel/contracts/Envelope.py applicationinsights/channel/contracts/EventData.py applicationinsights/channel/contracts/ExceptionData.py applicationinsights/channel/contracts/ExceptionDetails.py applicationinsights/channel/contracts/Internal.py applicationinsights/channel/contracts/Location.py applicationinsights/channel/contracts/MessageData.py applicationinsights/channel/contracts/MetricData.py applicationinsights/channel/contracts/Operation.py applicationinsights/channel/contracts/PageViewData.py applicationinsights/channel/contracts/RemoteDependencyData.py applicationinsights/channel/contracts/RequestData.py applicationinsights/channel/contracts/Session.py applicationinsights/channel/contracts/SeverityLevel.py applicationinsights/channel/contracts/StackFrame.py applicationinsights/channel/contracts/User.py applicationinsights/channel/contracts/Utils.py applicationinsights/channel/contracts/__init__.py applicationinsights/django/__init__.py applicationinsights/django/common.py applicationinsights/django/logging.py applicationinsights/django/middleware.py applicationinsights/exceptions/__init__.py applicationinsights/exceptions/enable.py applicationinsights/logging/LoggingHandler.py applicationinsights/logging/__init__.py applicationinsights/requests/WSGIApplication.py applicationinsights/requests/__init__.py tests/__init__.py tests/applicationinsights_tests/TestTelemetryClient.py tests/applicationinsights_tests/__init__.py tests/applicationinsights_tests/channel_tests/TestAsynchronousQueue.py tests/applicationinsights_tests/channel_tests/TestAsynchronousSender.py tests/applicationinsights_tests/channel_tests/TestQueueBase.py tests/applicationinsights_tests/channel_tests/TestSenderBase.py tests/applicationinsights_tests/channel_tests/TestSynchronousQueue.py tests/applicationinsights_tests/channel_tests/TestSynchronousSender.py tests/applicationinsights_tests/channel_tests/TestTelemetryChannel.py tests/applicationinsights_tests/channel_tests/TestTelemetryContext.py tests/applicationinsights_tests/channel_tests/__init__.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestApplication.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestData.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestDataPoint.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestDevice.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestEnvelope.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestEventData.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestExceptionData.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestExceptionDetails.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestInternal.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestLocation.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestMessageData.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestMetricData.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestOperation.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestPageViewData.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestRemoteDependencyData.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestRequestData.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestSession.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestStackFrame.py tests/applicationinsights_tests/channel_tests/contracts_tests/TestUser.py tests/applicationinsights_tests/channel_tests/contracts_tests/Utils.py tests/applicationinsights_tests/channel_tests/contracts_tests/__init__.py tests/applicationinsights_tests/exception_tests/TestEnable.py tests/applicationinsights_tests/exception_tests/__init__.py tests/applicationinsights_tests/logging_tests/TestLoggingHandler.py tests/applicationinsights_tests/logging_tests/__init__.py tests/applicationinsights_tests/requests_tests/TestWSGIApplication.py tests/applicationinsights_tests/requests_tests/__init__.pyapplicationinsights-0.11.0/applicationinsights.egg-info/top_level.txt0000644000076600000240000000002413145103565026363 0ustar alexbstaff00000000000000applicationinsights applicationinsights-0.11.0/DESCRIPTION.rst0000644000076600000240000001516013143420775020412 0ustar alexbstaff00000000000000Application Insights for Python =============================== This project extends the Application Insights API surface to support Python. `Application Insights `_ is a service that allows developers to keep their application available, performing and succeeding. This Python module will allow you to send telemetry of various kinds (event, trace, exception, etc.) to the Application Insights service where they can be visualized in the Azure Portal. Requirements ------------ Python 2.7 and Python 3.4 are currently supported by this module. For opening the project in Microsoft Visual Studio you will need `Python Tools for Visual Studio `_. Installation ------------ To install the latest release you can use `pip `_. :: $ pip install applicationinsights Usage ----- Once installed, you can send telemetry to Application Insights. Here are a few samples. **Note**: before you can send data to you will need an instrumentation key. Please see the `Getting an Application Insights Instrumentation Key `_ section for more information. **Sending a simple event telemetry item** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_event("Test event") tc.flush() **Sending an event telemetry item with custom properties and measurements** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_event('Test event', { 'foo': 'bar' }, { 'baz': 42 }) tc.flush() **Sending a trace telemetry item with custom properties** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_trace('Test trace', { 'foo': 'bar' }) tc.flush() **Sending a metric telemetry item** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_metric('My Metric', 42) tc.flush() **Sending an exception telemetry item with custom properties and measurements** .. code:: python import sys from applicationinsights import TelemetryClient tc = TelemetryClient('') try: raise Exception('blah') except: tc.track_exception() try: raise Exception("blah") except: tc.track_exception(*sys.exc_info(), properties={ 'foo': 'bar' }, measurements={ 'x': 42 }) tc.flush() **Configuring context for a telemetry client instance** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.context.application.id = 'My application' tc.context.application.ver = '1.2.3' tc.context.device.id = 'My current device' tc.context.device.oem_name = 'Asus' tc.context.device.model = 'X31A' tc.context.device.type = "Other" tc.context.user.id = 'santa@northpole.net' tc.track_trace('My trace with context') tc.flush() **Configuring channel related properties** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') # flush telemetry every 30 seconds (assuming we don't hit max_queue_item_count first) tc.channel.sender.send_interval_in_milliseconds = 30 * 1000 # flush telemetry if we have 10 or more telemetry items in our queue tc.channel.sender.max_queue_item_count = 10 **Basic logging configuration (first option)** .. code:: python import logging from applicationinsights.logging import enable # set up logging enable('') # log something (this will be sent to the Application Insights service as a trace) logging.info('This is a message') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively flush manually via handler.flush() **Basic logging configuration (second option)** .. code:: python import logging from applicationinsights.logging import LoggingHandler # set up logging handler = LoggingHandler('') logging.basicConfig(handlers=[ handler ], format='%(levelname)s: %(message)s', level=logging.DEBUG) # log something (this will be sent to the Application Insights service as a trace) logging.debug('This is a message') try: raise Exception('Some exception') except: # this will send an exception to the Application Insights service logging.exception('Code went boom!') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively flush manually via handler.flush() **Advanced logging configuration** .. code:: python import logging from applicationinsights.logging import LoggingHandler # set up logging handler = LoggingHandler('') handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s')) my_logger = logging.getLogger('simple_logger') my_logger.setLevel(logging.DEBUG) my_logger.addHandler(handler) # log something (this will be sent to the Application Insights service as a trace) my_logger.debug('This is a message') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively flush manually via handler.flush() **Logging unhandled exceptions** .. code:: python from applicationinsights.exceptions import enable # set up exception capture enable('') # raise an exception (this will be sent to the Application Insights service as an exception telemetry object) raise Exception('Boom!') **Logging requests** .. code:: python from flask import Flask from applicationinsights.requests import WSGIApplication # instantiate the Flask application and wrap its WSGI application app = Flask(__name__) app.wsgi_app = WSGIApplication('', app.wsgi_app) # define a simple route @app.route('/') def hello_world(): return 'Hello World!' # run the application if __name__ == '__main__': app.run() applicationinsights-0.11.0/LICENSE.txt0000644000076600000240000000206513143420775017720 0ustar alexbstaff00000000000000The MIT License (MIT) Copyright (c) 2014 Microsoft 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. applicationinsights-0.11.0/MANIFEST.in0000644000076600000240000000033513143420775017631 0ustar alexbstaff00000000000000include DESCRIPTION.rst include README.md include LICENSE.txt include Microsoft.ApplicationInsights.pyproj include Microsoft.ApplicationInsights.sln # Include the test suite recursive-include tests * global-exclude *.pyc applicationinsights-0.11.0/Microsoft.ApplicationInsights.pyproj0000644000076600000240000002536113143420775025266 0ustar alexbstaff00000000000000 Debug 2.0 adc6c556-02c1-4b21-bf8a-403d8bc8bce0 . . Microsoft.ApplicationInsights Microsoft.Telemetry {2af0f10d-7135-4994-9156-5d01c9c11b7e} 3.4 true false true false Code Code 12.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v12.0\Python Tools\Microsoft.PythonTools.targets applicationinsights-0.11.0/Microsoft.ApplicationInsights.sln0000644000076600000240000000153613143420775024535 0ustar alexbstaff00000000000000 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 VisualStudioVersion = 12.0.30723.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{888888A0-9F3D-457C-B088-3A5042F75D52}") = "Microsoft.ApplicationInsights", "Microsoft.ApplicationInsights.pyproj", "{ADC6C556-02C1-4B21-BF8A-403D8BC8BCE0}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {ADC6C556-02C1-4B21-BF8A-403D8BC8BCE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ADC6C556-02C1-4B21-BF8A-403D8BC8BCE0}.Release|Any CPU.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal applicationinsights-0.11.0/PKG-INFO0000644000076600000240000002172513145103565017173 0ustar alexbstaff00000000000000Metadata-Version: 1.1 Name: applicationinsights Version: 0.11.0 Summary: This project extends the Application Insights API surface to support Python. Home-page: https://github.com/Microsoft/AppInsights-Python Author: Microsoft Author-email: aiengdisc@microsoft.com License: MIT Download-URL: https://github.com/Microsoft/AppInsights-Python Description: Application Insights for Python =============================== This project extends the Application Insights API surface to support Python. `Application Insights `_ is a service that allows developers to keep their application available, performing and succeeding. This Python module will allow you to send telemetry of various kinds (event, trace, exception, etc.) to the Application Insights service where they can be visualized in the Azure Portal. Requirements ------------ Python 2.7 and Python 3.4 are currently supported by this module. For opening the project in Microsoft Visual Studio you will need `Python Tools for Visual Studio `_. Installation ------------ To install the latest release you can use `pip `_. :: $ pip install applicationinsights Usage ----- Once installed, you can send telemetry to Application Insights. Here are a few samples. **Note**: before you can send data to you will need an instrumentation key. Please see the `Getting an Application Insights Instrumentation Key `_ section for more information. **Sending a simple event telemetry item** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_event("Test event") tc.flush() **Sending an event telemetry item with custom properties and measurements** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_event('Test event', { 'foo': 'bar' }, { 'baz': 42 }) tc.flush() **Sending a trace telemetry item with custom properties** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_trace('Test trace', { 'foo': 'bar' }) tc.flush() **Sending a metric telemetry item** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_metric('My Metric', 42) tc.flush() **Sending an exception telemetry item with custom properties and measurements** .. code:: python import sys from applicationinsights import TelemetryClient tc = TelemetryClient('') try: raise Exception('blah') except: tc.track_exception() try: raise Exception("blah") except: tc.track_exception(*sys.exc_info(), properties={ 'foo': 'bar' }, measurements={ 'x': 42 }) tc.flush() **Configuring context for a telemetry client instance** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.context.application.id = 'My application' tc.context.application.ver = '1.2.3' tc.context.device.id = 'My current device' tc.context.device.oem_name = 'Asus' tc.context.device.model = 'X31A' tc.context.device.type = "Other" tc.context.user.id = 'santa@northpole.net' tc.track_trace('My trace with context') tc.flush() **Configuring channel related properties** .. code:: python from applicationinsights import TelemetryClient tc = TelemetryClient('') # flush telemetry every 30 seconds (assuming we don't hit max_queue_item_count first) tc.channel.sender.send_interval_in_milliseconds = 30 * 1000 # flush telemetry if we have 10 or more telemetry items in our queue tc.channel.sender.max_queue_item_count = 10 **Basic logging configuration (first option)** .. code:: python import logging from applicationinsights.logging import enable # set up logging enable('') # log something (this will be sent to the Application Insights service as a trace) logging.info('This is a message') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively flush manually via handler.flush() **Basic logging configuration (second option)** .. code:: python import logging from applicationinsights.logging import LoggingHandler # set up logging handler = LoggingHandler('') logging.basicConfig(handlers=[ handler ], format='%(levelname)s: %(message)s', level=logging.DEBUG) # log something (this will be sent to the Application Insights service as a trace) logging.debug('This is a message') try: raise Exception('Some exception') except: # this will send an exception to the Application Insights service logging.exception('Code went boom!') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively flush manually via handler.flush() **Advanced logging configuration** .. code:: python import logging from applicationinsights.logging import LoggingHandler # set up logging handler = LoggingHandler('') handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s')) my_logger = logging.getLogger('simple_logger') my_logger.setLevel(logging.DEBUG) my_logger.addHandler(handler) # log something (this will be sent to the Application Insights service as a trace) my_logger.debug('This is a message') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively flush manually via handler.flush() **Logging unhandled exceptions** .. code:: python from applicationinsights.exceptions import enable # set up exception capture enable('') # raise an exception (this will be sent to the Application Insights service as an exception telemetry object) raise Exception('Boom!') **Logging requests** .. code:: python from flask import Flask from applicationinsights.requests import WSGIApplication # instantiate the Flask application and wrap its WSGI application app = Flask(__name__) app.wsgi_app = WSGIApplication('', app.wsgi_app) # define a simple route @app.route('/') def hello_world(): return 'Hello World!' # run the application if __name__ == '__main__': app.run() Keywords: analytics applicationinsights telemetry appinsights development Platform: UNKNOWN Classifier: Development Status :: 3 - Alpha Classifier: Intended Audience :: Developers Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Operating System :: OS Independent Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.4 applicationinsights-0.11.0/README.md0000644000076600000240000002451413143421424017347 0ustar alexbstaff00000000000000# Application Insights for Python # [![Build Status](https://travis-ci.org/Microsoft/ApplicationInsights-Python.svg?branch=master)](https://travis-ci.org/Microsoft/ApplicationInsights-Python) [![PyPI version](https://badge.fury.io/py/applicationinsights.svg)](http://badge.fury.io/py/applicationinsights) This project extends the Application Insights API surface to support Python. [Application Insights](http://azure.microsoft.com/en-us/services/application-insights/) is a service that allows developers to keep their application available, performing and succeeding. This Python module will allow you to send telemetry of various kinds (event, trace, exception, etc.) to the Application Insights service where they can be visualized in the Azure Portal. ## Requirements ## Python >=2.7 and Python >=3.4 are currently supported by this module. For opening the project in Microsoft Visual Studio you will need [Python Tools for Visual Studio](http://pytools.codeplex.com/). ## Installation ## To install the latest release you can use [pip](http://www.pip-installer.org/). ``` $ pip install applicationinsights ``` ## Usage ## Once installed, you can send telemetry to Application Insights. Here are a few samples. >**Note**: before you can send data to you will need an instrumentation key. Please see the [Getting an Application Insights Instrumentation Key](https://github.com/Microsoft/AppInsights-Home/wiki#getting-an-application-insights-instrumentation-key) section for more information. **Sending a simple event telemetry item** ```python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_event('Test event') tc.flush() ``` **Sending an event telemetry item with custom properties and measurements** ```python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_event('Test event', { 'foo': 'bar' }, { 'baz': 42 }) tc.flush() ``` **Sending a trace telemetry item with custom properties** ```python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_trace('Test trace', { 'foo': 'bar' }) tc.flush() ``` **Sending a metric telemetry item** ```python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.track_metric('My Metric', 42) tc.flush() ``` **Sending an exception telemetry item with custom properties and measurements** ```python import sys from applicationinsights import TelemetryClient tc = TelemetryClient('') try: raise Exception('blah') except: tc.track_exception() try: raise Exception("blah") except: tc.track_exception(*sys.exc_info(), properties={ 'foo': 'bar' }, measurements={ 'x': 42 }) tc.flush() ``` **Configuring context for a telemetry client instance** ```python from applicationinsights import TelemetryClient tc = TelemetryClient('') tc.context.application.id = 'My application' tc.context.application.ver = '1.2.3' tc.context.device.id = 'My current device' tc.context.device.oem_name = 'Asus' tc.context.device.model = 'X31A' tc.context.device.type = "Other" tc.context.user.id = 'santa@northpole.net' tc.track_trace('My trace with context') tc.flush() ``` **Configuring channel related properties** ```python from applicationinsights import TelemetryClient tc = TelemetryClient('') # flush telemetry every 30 seconds (assuming we don't hit max_queue_item_count first) tc.channel.sender.send_interval_in_milliseconds = 30 * 1000 # flush telemetry if we have 10 or more telemetry items in our queue tc.channel.sender.max_queue_item_count = 10 ``` **Basic logging configuration (first option)** ```python import logging from applicationinsights.logging import enable # set up logging enable('') # log something (this will be sent to the Application Insights service as a trace) logging.info('This is a message') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively flush manually via handler.flush() ``` **Basic logging configuration (second option)** ```python import logging from applicationinsights.logging import LoggingHandler # set up logging handler = LoggingHandler('') logging.basicConfig(handlers=[ handler ], format='%(levelname)s: %(message)s', level=logging.DEBUG) # log something (this will be sent to the Application Insights service as a trace) logging.debug('This is a message') try: raise Exception('Some exception') except: # this will send an exception to the Application Insights service logging.exception('Code went boom!') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively flush manually via handler.flush() ``` **Advanced logging configuration** ```python import logging from applicationinsights.logging import LoggingHandler # set up logging handler = LoggingHandler('') handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s')) my_logger = logging.getLogger('simple_logger') my_logger.setLevel(logging.DEBUG) my_logger.addHandler(handler) # log something (this will be sent to the Application Insights service as a trace) my_logger.debug('This is a message') # logging shutdown will cause a flush of all un-sent telemetry items # alternatively flush manually via handler.flush() ``` **Logging unhandled exceptions** ```python from applicationinsights.exceptions import enable # set up exception capture enable('') # raise an exception (this will be sent to the Application Insights service as an exception telemetry object) raise Exception('Boom!') ``` **Logging requests** ```python from flask import Flask from applicationinsights.requests import WSGIApplication # instantiate the Flask application and wrap its WSGI application app = Flask(__name__) app.wsgi_app = WSGIApplication('', app.wsgi_app) # define a simple route @app.route('/') def hello_world(): return 'Hello World!' # run the application if __name__ == '__main__': app.run() ``` **Integrating with Django** Place the following in your `settings.py` file: ```python # If on Django < 1.10 MIDDLEWARE_CLASSES = [ # ... or whatever is below for you ... 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # ... or whatever is above for you ... 'applicationinsights.django.ApplicationInsightsMiddleware', # Add this middleware to the end ] # If on Django >= 1.10 MIDDLEWARE = [ # ... or whatever is below for you ... 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # ... or whatever is above for you ... 'applicationinsights.django.ApplicationInsightsMiddleware', # Add this middleware to the end ] APPLICATION_INSIGHTS = { # (required) Your Application Insights instrumentation key 'ikey': "00000000-0000-0000-0000-000000000000", # (optional) By default, request names are logged as the request method # and relative path of the URL. To log the fully-qualified view names # instead, set this to True. Defaults to False. 'use_view_name': True, # (optional) To log arguments passed into the views as custom properties, # set this to True. Defaults to False. 'record_view_arguments': True, # (optional) Exceptions are logged by default, to disable, set this to False. 'log_exceptions': False, # (optional) Events are submitted to Application Insights asynchronously. # send_interval specifies how often the queue is checked for items to submit. # send_time specifies how long the sender waits for new input before recycling # the background thread. 'send_interval': 1.0, # Check every second 'send_time': 3.0, # Wait up to 3 seconds for an event # (optional, uncommon) If you must send to an endpoint other than the # default endpoint, specify it here: 'endpoint': "https://dc.services.visualstudio.com/v2/track", } ``` This will log all requests and exceptions to the instrumentation key specified in the `APPLICATION_INSIGHTS` setting. In addition, an `appinsights` property will be placed on each incoming `request` object in your views. This will have the following properties: * `client`: This is an instance of the `applicationinsights.TelemetryClient` type, which will submit telemetry to the same instrumentation key, and will parent each telemetry item to the current request. * `request`: This is the `applicationinsights.channel.contracts.RequestData` instance for the current request. You can modify properties on this object during the handling of the current request. It will be submitted when the request has finished. * `context`: This is the `applicationinsights.channel.TelemetryContext` object for the current ApplicationInsights sender. You can also hook up logging to Django. For example, to log all builtin Django warnings and errors, use the following logging configuration in `settings.py`: ```python LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { # The application insights handler is here 'appinsights': { 'class': 'applicationinsights.django.LoggingHandler', 'level': 'WARNING' } }, 'loggers': { 'django': { 'handlers': ['appinsights'], 'level': 'WARNING', 'propagate': True, } } } ``` See Django's [logging documentation](https://docs.djangoproject.com/en/1.11/topics/logging/) for more information. applicationinsights-0.11.0/setup.cfg0000644000076600000240000000013013145103565017702 0ustar alexbstaff00000000000000[bdist_wheel] universal = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 applicationinsights-0.11.0/setup.py0000644000076600000240000000440713145103457017606 0ustar alexbstaff00000000000000from setuptools import setup, find_packages # Always prefer setuptools over distutils from codecs import open # To use a consistent encoding from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='applicationinsights', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # http://packaging.python.org/en/latest/tutorial.html#version version='0.11.0', description='This project extends the Application Insights API surface to support Python.', long_description=long_description, # The project's main homepage. url='https://github.com/Microsoft/AppInsights-Python', download_url='https://github.com/Microsoft/AppInsights-Python', # Author details author='Microsoft', author_email='aiengdisc@microsoft.com', # Choose your license license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', # operating systems 'Operating System :: OS Independent', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ], # What does your project relate to? keywords='analytics applicationinsights telemetry appinsights development', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['contrib', 'docs', 'tests*']), test_suite='tests.applicationinsights_tests' ) applicationinsights-0.11.0/tests/0000755000076600000240000000000013145103565017231 5ustar alexbstaff00000000000000applicationinsights-0.11.0/tests/__init__.py0000644000076600000240000000000013143420775021333 0ustar alexbstaff00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/0000755000076600000240000000000013145103565024527 5ustar alexbstaff00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/__init__.py0000644000076600000240000000022413143420775026641 0ustar alexbstaff00000000000000from . import TestTelemetryClient from . import channel_tests from . import exception_tests from . import logging_tests from . import requests_testsapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/0000755000076600000240000000000013145103565027361 5ustar alexbstaff00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/__init__.py0000644000076600000240000000045413143420775031500 0ustar alexbstaff00000000000000from . import TestAsynchronousQueue from . import TestAsynchronousSender from . import TestQueueBase from . import TestSenderBase from . import TestSynchronousQueue from . import TestSynchronousSender from . import TestTelemetryChannel from . import TestTelemetryContext from . import contracts_testsapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/0000755000076600000240000000000013145103565032603 5ustar alexbstaff00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/__init__.py0000644000076600000240000000145113143420775034720 0ustar alexbstaff00000000000000from .TestData import TestData from .TestEnvelope import TestEnvelope from .TestDataPoint import TestDataPoint from .TestMetricData import TestMetricData from .TestRemoteDependencyData import TestRemoteDependencyData from .TestRequestData import TestRequestData from .TestStackFrame import TestStackFrame from .TestExceptionDetails import TestExceptionDetails from .TestExceptionData import TestExceptionData from .TestMessageData import TestMessageData from .TestEventData import TestEventData from .TestPageViewData import TestPageViewData from .TestApplication import TestApplication from .TestDevice import TestDevice from .TestLocation import TestLocation from .TestOperation import TestOperation from .TestSession import TestSession from .TestUser import TestUser from .TestInternal import TestInternal ././@LongLink0000000000000000000000000000015400000000000011215 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestApplication.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestApplica0000644000076600000240000000216513143420775034746 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestApplication(unittest.TestCase): def test_construct(self): item = Application() self.assertNotEqual(item, None) def test_ver_property_works_as_expected(self): expected = 'Test string' item = Application() item.ver = expected actual = item.ver self.assertEqual(expected, actual) expected = 'Other string' item.ver = expected actual = item.ver self.assertEqual(expected, actual) def test_serialize_works_as_expected(self): item = Application() item.ver = 'Test string' actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ai.application.ver":"Test string"}' self.assertEqual(expected, actual) applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestData.py0000644000076600000240000000301113143420775034664 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestData(unittest.TestCase): def test_construct(self): item = Data() self.assertNotEqual(item, None) def test_base_type_property_works_as_expected(self): expected = 'Test string' item = Data() item.base_type = expected actual = item.base_type self.assertEqual(expected, actual) expected = 'Other string' item.base_type = expected actual = item.base_type self.assertEqual(expected, actual) def test_base_data_property_works_as_expected(self): expected = object() item = Data() item.base_data = expected actual = item.base_data self.assertEqual(expected, actual) expected = object() item.base_data = expected actual = item.base_data self.assertEqual(expected, actual) def test_serialize_works_as_expected(self): item = Data() item.base_type = 'Test string' item.base_data = object() actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"baseType":"Test string","baseData":{}}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000015200000000000011213 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestDataPoint.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestDataPoi0000644000076600000240000000640513143420775034717 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestDataPoint(unittest.TestCase): def test_construct(self): item = DataPoint() self.assertNotEqual(item, None) def test_name_property_works_as_expected(self): expected = 'Test string' item = DataPoint() item.name = expected actual = item.name self.assertEqual(expected, actual) expected = 'Other string' item.name = expected actual = item.name self.assertEqual(expected, actual) def test_kind_property_works_as_expected(self): expected = object() item = DataPoint() item.kind = expected actual = item.kind self.assertEqual(expected, actual) expected = object() item.kind = expected actual = item.kind self.assertEqual(expected, actual) def test_value_property_works_as_expected(self): expected = 1.5 item = DataPoint() item.value = expected actual = item.value self.assertEqual(expected, actual) expected = 4.8 item.value = expected actual = item.value self.assertEqual(expected, actual) def test_count_property_works_as_expected(self): expected = 42 item = DataPoint() item.count = expected actual = item.count self.assertEqual(expected, actual) expected = 13 item.count = expected actual = item.count self.assertEqual(expected, actual) def test_min_property_works_as_expected(self): expected = 1.5 item = DataPoint() item.min = expected actual = item.min self.assertEqual(expected, actual) expected = 4.8 item.min = expected actual = item.min self.assertEqual(expected, actual) def test_max_property_works_as_expected(self): expected = 1.5 item = DataPoint() item.max = expected actual = item.max self.assertEqual(expected, actual) expected = 4.8 item.max = expected actual = item.max self.assertEqual(expected, actual) def test_std_dev_property_works_as_expected(self): expected = 1.5 item = DataPoint() item.std_dev = expected actual = item.std_dev self.assertEqual(expected, actual) expected = 4.8 item.std_dev = expected actual = item.std_dev self.assertEqual(expected, actual) def test_serialize_works_as_expected(self): item = DataPoint() item.name = 'Test string' item.kind = object() item.value = 1.5 item.count = 42 item.min = 1.5 item.max = 1.5 item.std_dev = 1.5 actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"name":"Test string","kind":{},"value":1.5,"count":42,"min":1.5,"max":1.5,"stdDev":1.5}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000014700000000000011217 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestDevice.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestDevice.0000644000076600000240000001516013143420775034651 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestDevice(unittest.TestCase): def test_construct(self): item = Device() self.assertNotEqual(item, None) def test_id_property_works_as_expected(self): expected = 'Test string' item = Device() item.id = expected actual = item.id self.assertEqual(expected, actual) expected = 'Other string' item.id = expected actual = item.id self.assertEqual(expected, actual) def test_ip_property_works_as_expected(self): expected = 'Test string' item = Device() item.ip = expected actual = item.ip self.assertEqual(expected, actual) expected = 'Other string' item.ip = expected actual = item.ip self.assertEqual(expected, actual) def test_language_property_works_as_expected(self): expected = 'Test string' item = Device() item.language = expected actual = item.language self.assertEqual(expected, actual) expected = 'Other string' item.language = expected actual = item.language self.assertEqual(expected, actual) def test_locale_property_works_as_expected(self): expected = 'Test string' item = Device() item.locale = expected actual = item.locale self.assertEqual(expected, actual) expected = 'Other string' item.locale = expected actual = item.locale self.assertEqual(expected, actual) def test_model_property_works_as_expected(self): expected = 'Test string' item = Device() item.model = expected actual = item.model self.assertEqual(expected, actual) expected = 'Other string' item.model = expected actual = item.model self.assertEqual(expected, actual) def test_network_property_works_as_expected(self): expected = 'Test string' item = Device() item.network = expected actual = item.network self.assertEqual(expected, actual) expected = 'Other string' item.network = expected actual = item.network self.assertEqual(expected, actual) def test_oem_name_property_works_as_expected(self): expected = 'Test string' item = Device() item.oem_name = expected actual = item.oem_name self.assertEqual(expected, actual) expected = 'Other string' item.oem_name = expected actual = item.oem_name self.assertEqual(expected, actual) def test_os_property_works_as_expected(self): expected = 'Test string' item = Device() item.os = expected actual = item.os self.assertEqual(expected, actual) expected = 'Other string' item.os = expected actual = item.os self.assertEqual(expected, actual) def test_os_version_property_works_as_expected(self): expected = 'Test string' item = Device() item.os_version = expected actual = item.os_version self.assertEqual(expected, actual) expected = 'Other string' item.os_version = expected actual = item.os_version self.assertEqual(expected, actual) def test_role_instance_property_works_as_expected(self): expected = 'Test string' item = Device() item.role_instance = expected actual = item.role_instance self.assertEqual(expected, actual) expected = 'Other string' item.role_instance = expected actual = item.role_instance self.assertEqual(expected, actual) def test_role_name_property_works_as_expected(self): expected = 'Test string' item = Device() item.role_name = expected actual = item.role_name self.assertEqual(expected, actual) expected = 'Other string' item.role_name = expected actual = item.role_name self.assertEqual(expected, actual) def test_screen_resolution_property_works_as_expected(self): expected = 'Test string' item = Device() item.screen_resolution = expected actual = item.screen_resolution self.assertEqual(expected, actual) expected = 'Other string' item.screen_resolution = expected actual = item.screen_resolution self.assertEqual(expected, actual) def test_type_property_works_as_expected(self): expected = 'Test string' item = Device() item.type = expected actual = item.type self.assertEqual(expected, actual) expected = 'Other string' item.type = expected actual = item.type self.assertEqual(expected, actual) def test_vm_name_property_works_as_expected(self): expected = 'Test string' item = Device() item.vm_name = expected actual = item.vm_name self.assertEqual(expected, actual) expected = 'Other string' item.vm_name = expected actual = item.vm_name self.assertEqual(expected, actual) def test_serialize_works_as_expected(self): item = Device() item.id = 'Test string' item.ip = 'Test string' item.language = 'Test string' item.locale = 'Test string' item.model = 'Test string' item.network = 'Test string' item.oem_name = 'Test string' item.os = 'Test string' item.os_version = 'Test string' item.role_instance = 'Test string' item.role_name = 'Test string' item.screen_resolution = 'Test string' item.type = 'Test string' item.vm_name = 'Test string' actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ai.device.id":"Test string","ai.device.ip":"Test string","ai.device.language":"Test string","ai.device.locale":"Test string","ai.device.model":"Test string","ai.device.network":"Test string","ai.device.oemName":"Test string","ai.device.os":"Test string","ai.device.osVersion":"Test string","ai.device.roleInstance":"Test string","ai.device.roleName":"Test string","ai.device.screenResolution":"Test string","ai.device.type":"Test string","ai.device.vmName":"Test string"}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000015100000000000011212 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestEnvelope.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestEnvelop0000644000076600000240000001500013143420775034775 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestEnvelope(unittest.TestCase): def test_construct(self): item = Envelope() self.assertNotEqual(item, None) def test_ver_property_works_as_expected(self): expected = 42 item = Envelope() item.ver = expected actual = item.ver self.assertEqual(expected, actual) expected = 13 item.ver = expected actual = item.ver self.assertEqual(expected, actual) def test_name_property_works_as_expected(self): expected = 'Test string' item = Envelope() item.name = expected actual = item.name self.assertEqual(expected, actual) expected = 'Other string' item.name = expected actual = item.name self.assertEqual(expected, actual) def test_time_property_works_as_expected(self): expected = 'Test string' item = Envelope() item.time = expected actual = item.time self.assertEqual(expected, actual) expected = 'Other string' item.time = expected actual = item.time self.assertEqual(expected, actual) def test_sample_rate_property_works_as_expected(self): expected = 1.5 item = Envelope() item.sample_rate = expected actual = item.sample_rate self.assertEqual(expected, actual) expected = 4.8 item.sample_rate = expected actual = item.sample_rate self.assertEqual(expected, actual) def test_seq_property_works_as_expected(self): expected = 'Test string' item = Envelope() item.seq = expected actual = item.seq self.assertEqual(expected, actual) expected = 'Other string' item.seq = expected actual = item.seq self.assertEqual(expected, actual) def test_ikey_property_works_as_expected(self): expected = 'Test string' item = Envelope() item.ikey = expected actual = item.ikey self.assertEqual(expected, actual) expected = 'Other string' item.ikey = expected actual = item.ikey self.assertEqual(expected, actual) def test_flags_property_works_as_expected(self): expected = 42 item = Envelope() item.flags = expected actual = item.flags self.assertEqual(expected, actual) expected = 13 item.flags = expected actual = item.flags self.assertEqual(expected, actual) def test_device_id_property_works_as_expected(self): expected = 'Test string' item = Envelope() item.device_id = expected actual = item.device_id self.assertEqual(expected, actual) expected = 'Other string' item.device_id = expected actual = item.device_id self.assertEqual(expected, actual) def test_os_property_works_as_expected(self): expected = 'Test string' item = Envelope() item.os = expected actual = item.os self.assertEqual(expected, actual) expected = 'Other string' item.os = expected actual = item.os self.assertEqual(expected, actual) def test_os_ver_property_works_as_expected(self): expected = 'Test string' item = Envelope() item.os_ver = expected actual = item.os_ver self.assertEqual(expected, actual) expected = 'Other string' item.os_ver = expected actual = item.os_ver self.assertEqual(expected, actual) def test_app_id_property_works_as_expected(self): expected = 'Test string' item = Envelope() item.app_id = expected actual = item.app_id self.assertEqual(expected, actual) expected = 'Other string' item.app_id = expected actual = item.app_id self.assertEqual(expected, actual) def test_app_ver_property_works_as_expected(self): expected = 'Test string' item = Envelope() item.app_ver = expected actual = item.app_ver self.assertEqual(expected, actual) expected = 'Other string' item.app_ver = expected actual = item.app_ver self.assertEqual(expected, actual) def test_user_id_property_works_as_expected(self): expected = 'Test string' item = Envelope() item.user_id = expected actual = item.user_id self.assertEqual(expected, actual) expected = 'Other string' item.user_id = expected actual = item.user_id self.assertEqual(expected, actual) def test_tags_property_works_as_expected(self): item = Envelope() actual = item.tags self.assertNotEqual(actual, None) def test_data_property_works_as_expected(self): expected = object() item = Envelope() item.data = expected actual = item.data self.assertEqual(expected, actual) expected = object() item.data = expected actual = item.data self.assertEqual(expected, actual) def test_serialize_works_as_expected(self): item = Envelope() item.ver = 42 item.name = 'Test string' item.time = 'Test string' item.sample_rate = 1.5 item.seq = 'Test string' item.ikey = 'Test string' item.flags = 42 item.device_id = 'Test string' item.os = 'Test string' item.os_ver = 'Test string' item.app_id = 'Test string' item.app_ver = 'Test string' item.user_id = 'Test string' for key, value in { 'key1': 'test value 1' , 'key2': 'test value 2' }.items(): item.tags[key] = value item.data = object() actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ver":42,"name":"Test string","time":"Test string","sampleRate":1.5,"seq":"Test string","iKey":"Test string","flags":42,"deviceId":"Test string","os":"Test string","osVer":"Test string","appId":"Test string","appVer":"Test string","userId":"Test string","tags":{"key1":"test value 1","key2":"test value 2"},"data":{}}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000015200000000000011213 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestEventData.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestEventDa0000644000076600000240000000415113143420775034720 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestEventData(unittest.TestCase): def test_construct(self): item = EventData() self.assertNotEqual(item, None) def test_ver_property_works_as_expected(self): expected = 42 item = EventData() item.ver = expected actual = item.ver self.assertEqual(expected, actual) expected = 13 item.ver = expected actual = item.ver self.assertEqual(expected, actual) def test_name_property_works_as_expected(self): expected = 'Test string' item = EventData() item.name = expected actual = item.name self.assertEqual(expected, actual) expected = 'Other string' item.name = expected actual = item.name self.assertEqual(expected, actual) def test_properties_property_works_as_expected(self): item = EventData() actual = item.properties self.assertNotEqual(actual, None) def test_measurements_property_works_as_expected(self): item = EventData() actual = item.measurements self.assertNotEqual(actual, None) def test_serialize_works_as_expected(self): item = EventData() item.ver = 42 item.name = 'Test string' for key, value in { 'key1': 'test value 1' , 'key2': 'test value 2' }.items(): item.properties[key] = value for key, value in { 'key1': 3.1415 , 'key2': 42.2 }.items(): item.measurements[key] = value actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ver":42,"name":"Test string","properties":{"key1":"test value 1","key2":"test value 2"},"measurements":{"key1":3.1415,"key2":42.2}}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000015600000000000011217 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestExceptionData.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestExcepti0000644000076600000240000000560113143420775034774 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestExceptionData(unittest.TestCase): def test_construct(self): item = ExceptionData() self.assertNotEqual(item, None) def test_ver_property_works_as_expected(self): expected = 42 item = ExceptionData() item.ver = expected actual = item.ver self.assertEqual(expected, actual) expected = 13 item.ver = expected actual = item.ver self.assertEqual(expected, actual) def test_handled_at_property_works_as_expected(self): expected = 'Test string' item = ExceptionData() item.handled_at = expected actual = item.handled_at self.assertEqual(expected, actual) expected = 'Other string' item.handled_at = expected actual = item.handled_at self.assertEqual(expected, actual) def test_exceptions_property_works_as_expected(self): item = ExceptionData() actual = item.exceptions self.assertNotEqual(actual, None) def test_severity_level_property_works_as_expected(self): expected = object() item = ExceptionData() item.severity_level = expected actual = item.severity_level self.assertEqual(expected, actual) expected = object() item.severity_level = expected actual = item.severity_level self.assertEqual(expected, actual) def test_properties_property_works_as_expected(self): item = ExceptionData() actual = item.properties self.assertNotEqual(actual, None) def test_measurements_property_works_as_expected(self): item = ExceptionData() actual = item.measurements self.assertNotEqual(actual, None) def test_serialize_works_as_expected(self): item = ExceptionData() item.ver = 42 item.handled_at = 'Test string' for value in [ object() ]: item.exceptions.append(value) item.severity_level = object() for key, value in { 'key1': 'test value 1' , 'key2': 'test value 2' }.items(): item.properties[key] = value for key, value in { 'key1': 3.1415 , 'key2': 42.2 }.items(): item.measurements[key] = value actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ver":42,"handledAt":"Test string","exceptions":[{}],"severityLevel":{},"properties":{"key1":"test value 1","key2":"test value 2"},"measurements":{"key1":3.1415,"key2":42.2}}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000016100000000000011213 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestExceptionDetails.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestExcepti0000644000076600000240000000666413143420775035006 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestExceptionDetails(unittest.TestCase): def test_construct(self): item = ExceptionDetails() self.assertNotEqual(item, None) def test_id_property_works_as_expected(self): expected = 42 item = ExceptionDetails() item.id = expected actual = item.id self.assertEqual(expected, actual) expected = 13 item.id = expected actual = item.id self.assertEqual(expected, actual) def test_outer_id_property_works_as_expected(self): expected = 42 item = ExceptionDetails() item.outer_id = expected actual = item.outer_id self.assertEqual(expected, actual) expected = 13 item.outer_id = expected actual = item.outer_id self.assertEqual(expected, actual) def test_type_name_property_works_as_expected(self): expected = 'Test string' item = ExceptionDetails() item.type_name = expected actual = item.type_name self.assertEqual(expected, actual) expected = 'Other string' item.type_name = expected actual = item.type_name self.assertEqual(expected, actual) def test_message_property_works_as_expected(self): expected = 'Test string' item = ExceptionDetails() item.message = expected actual = item.message self.assertEqual(expected, actual) expected = 'Other string' item.message = expected actual = item.message self.assertEqual(expected, actual) def test_has_full_stack_property_works_as_expected(self): expected = True item = ExceptionDetails() item.has_full_stack = expected actual = item.has_full_stack self.assertEqual(expected, actual) expected = False item.has_full_stack = expected actual = item.has_full_stack self.assertEqual(expected, actual) def test_stack_property_works_as_expected(self): expected = 'Test string' item = ExceptionDetails() item.stack = expected actual = item.stack self.assertEqual(expected, actual) expected = 'Other string' item.stack = expected actual = item.stack self.assertEqual(expected, actual) def test_parsed_stack_property_works_as_expected(self): item = ExceptionDetails() actual = item.parsed_stack self.assertNotEqual(actual, None) def test_serialize_works_as_expected(self): item = ExceptionDetails() item.id = 42 item.outer_id = 42 item.type_name = 'Test string' item.message = 'Test string' item.has_full_stack = True item.stack = 'Test string' for value in [ object() ]: item.parsed_stack.append(value) actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"id":42,"outerId":42,"typeName":"Test string","message":"Test string","hasFullStack":true,"stack":"Test string","parsedStack":[{}]}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000015100000000000011212 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestInternal.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestInterna0000644000076600000240000000317213143420775034774 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestInternal(unittest.TestCase): def test_construct(self): item = Internal() self.assertNotEqual(item, None) def test_sdk_version_property_works_as_expected(self): expected = 'Test string' item = Internal() item.sdk_version = expected actual = item.sdk_version self.assertEqual(expected, actual) expected = 'Other string' item.sdk_version = expected actual = item.sdk_version self.assertEqual(expected, actual) def test_agent_version_property_works_as_expected(self): expected = 'Test string' item = Internal() item.agent_version = expected actual = item.agent_version self.assertEqual(expected, actual) expected = 'Other string' item.agent_version = expected actual = item.agent_version self.assertEqual(expected, actual) def test_serialize_works_as_expected(self): item = Internal() item.sdk_version = 'Test string' item.agent_version = 'Test string' actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ai.internal.sdkVersion":"Test string","ai.internal.agentVersion":"Test string"}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000015100000000000011212 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestLocation.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestLocatio0000644000076600000240000000213713143420775034766 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestLocation(unittest.TestCase): def test_construct(self): item = Location() self.assertNotEqual(item, None) def test_ip_property_works_as_expected(self): expected = 'Test string' item = Location() item.ip = expected actual = item.ip self.assertEqual(expected, actual) expected = 'Other string' item.ip = expected actual = item.ip self.assertEqual(expected, actual) def test_serialize_works_as_expected(self): item = Location() item.ip = 'Test string' actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ai.location.ip":"Test string"}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000015400000000000011215 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestMessageData.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestMessage0000644000076600000240000000440613143420775034761 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestMessageData(unittest.TestCase): def test_construct(self): item = MessageData() self.assertNotEqual(item, None) def test_ver_property_works_as_expected(self): expected = 42 item = MessageData() item.ver = expected actual = item.ver self.assertEqual(expected, actual) expected = 13 item.ver = expected actual = item.ver self.assertEqual(expected, actual) def test_message_property_works_as_expected(self): expected = 'Test string' item = MessageData() item.message = expected actual = item.message self.assertEqual(expected, actual) expected = 'Other string' item.message = expected actual = item.message self.assertEqual(expected, actual) def test_severity_level_property_works_as_expected(self): expected = object() item = MessageData() item.severity_level = expected actual = item.severity_level self.assertEqual(expected, actual) expected = object() item.severity_level = expected actual = item.severity_level self.assertEqual(expected, actual) def test_properties_property_works_as_expected(self): item = MessageData() actual = item.properties self.assertNotEqual(actual, None) def test_serialize_works_as_expected(self): item = MessageData() item.ver = 42 item.message = 'Test string' item.severity_level = object() for key, value in { 'key1': 'test value 1' , 'key2': 'test value 2' }.items(): item.properties[key] = value actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ver":42,"message":"Test string","severityLevel":{},"properties":{"key1":"test value 1","key2":"test value 2"}}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000015300000000000011214 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestMetricData.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestMetricD0000644000076600000240000000323013143420775034716 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestMetricData(unittest.TestCase): def test_construct(self): item = MetricData() self.assertNotEqual(item, None) def test_ver_property_works_as_expected(self): expected = 42 item = MetricData() item.ver = expected actual = item.ver self.assertEqual(expected, actual) expected = 13 item.ver = expected actual = item.ver self.assertEqual(expected, actual) def test_metrics_property_works_as_expected(self): item = MetricData() actual = item.metrics self.assertNotEqual(actual, None) def test_properties_property_works_as_expected(self): item = MetricData() actual = item.properties self.assertNotEqual(actual, None) def test_serialize_works_as_expected(self): item = MetricData() item.ver = 42 for value in [ object() ]: item.metrics.append(value) for key, value in { 'key1': 'test value 1' , 'key2': 'test value 2' }.items(): item.properties[key] = value actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ver":42,"metrics":[{}],"properties":{"key1":"test value 1","key2":"test value 2"}}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000015200000000000011213 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestOperation.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestOperati0000644000076600000240000000457513143420775035007 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestOperation(unittest.TestCase): def test_construct(self): item = Operation() self.assertNotEqual(item, None) def test_id_property_works_as_expected(self): expected = 'Test string' item = Operation() item.id = expected actual = item.id self.assertEqual(expected, actual) expected = 'Other string' item.id = expected actual = item.id self.assertEqual(expected, actual) def test_name_property_works_as_expected(self): expected = 'Test string' item = Operation() item.name = expected actual = item.name self.assertEqual(expected, actual) expected = 'Other string' item.name = expected actual = item.name self.assertEqual(expected, actual) def test_parent_id_property_works_as_expected(self): expected = 'Test string' item = Operation() item.parent_id = expected actual = item.parent_id self.assertEqual(expected, actual) expected = 'Other string' item.parent_id = expected actual = item.parent_id self.assertEqual(expected, actual) def test_root_id_property_works_as_expected(self): expected = 'Test string' item = Operation() item.root_id = expected actual = item.root_id self.assertEqual(expected, actual) expected = 'Other string' item.root_id = expected actual = item.root_id self.assertEqual(expected, actual) def test_serialize_works_as_expected(self): item = Operation() item.id = 'Test string' item.name = 'Test string' item.parent_id = 'Test string' item.root_id = 'Test string' actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ai.operation.id":"Test string","ai.operation.name":"Test string","ai.operation.parentId":"Test string","ai.operation.rootId":"Test string"}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000015500000000000011216 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestPageViewData.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestPageVie0000644000076600000240000000570113143420775034714 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestPageViewData(unittest.TestCase): def test_construct(self): item = PageViewData() self.assertNotEqual(item, None) def test_ver_property_works_as_expected(self): expected = 42 item = PageViewData() item.ver = expected actual = item.ver self.assertEqual(expected, actual) expected = 13 item.ver = expected actual = item.ver self.assertEqual(expected, actual) def test_url_property_works_as_expected(self): expected = 'Test string' item = PageViewData() item.url = expected actual = item.url self.assertEqual(expected, actual) expected = 'Other string' item.url = expected actual = item.url self.assertEqual(expected, actual) def test_name_property_works_as_expected(self): expected = 'Test string' item = PageViewData() item.name = expected actual = item.name self.assertEqual(expected, actual) expected = 'Other string' item.name = expected actual = item.name self.assertEqual(expected, actual) def test_duration_property_works_as_expected(self): expected = 'Test string' item = PageViewData() item.duration = expected actual = item.duration self.assertEqual(expected, actual) expected = 'Other string' item.duration = expected actual = item.duration self.assertEqual(expected, actual) def test_properties_property_works_as_expected(self): item = PageViewData() actual = item.properties self.assertNotEqual(actual, None) def test_measurements_property_works_as_expected(self): item = PageViewData() actual = item.measurements self.assertNotEqual(actual, None) def test_serialize_works_as_expected(self): item = PageViewData() item.ver = 42 item.url = 'Test string' item.name = 'Test string' item.duration = 'Test string' for key, value in { 'key1': 'test value 1' , 'key2': 'test value 2' }.items(): item.properties[key] = value for key, value in { 'key1': 3.1415 , 'key2': 42.2 }.items(): item.measurements[key] = value actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ver":42,"url":"Test string","name":"Test string","duration":"Test string","properties":{"key1":"test value 1","key2":"test value 2"},"measurements":{"key1":3.1415,"key2":42.2}}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000016500000000000011217 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestRemoteDependencyData.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestRemoteD0000644000076600000240000001341113143420775034730 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestRemoteDependencyData(unittest.TestCase): def test_construct(self): item = RemoteDependencyData() self.assertNotEqual(item, None) def test_ver_property_works_as_expected(self): expected = 42 item = RemoteDependencyData() item.ver = expected actual = item.ver self.assertEqual(expected, actual) expected = 13 item.ver = expected actual = item.ver self.assertEqual(expected, actual) def test_name_property_works_as_expected(self): expected = 'Test string' item = RemoteDependencyData() item.name = expected actual = item.name self.assertEqual(expected, actual) expected = 'Other string' item.name = expected actual = item.name self.assertEqual(expected, actual) def test_kind_property_works_as_expected(self): expected = object() item = RemoteDependencyData() item.kind = expected actual = item.kind self.assertEqual(expected, actual) expected = object() item.kind = expected actual = item.kind self.assertEqual(expected, actual) def test_value_property_works_as_expected(self): expected = 1.5 item = RemoteDependencyData() item.value = expected actual = item.value self.assertEqual(expected, actual) expected = 4.8 item.value = expected actual = item.value self.assertEqual(expected, actual) def test_count_property_works_as_expected(self): expected = 42 item = RemoteDependencyData() item.count = expected actual = item.count self.assertEqual(expected, actual) expected = 13 item.count = expected actual = item.count self.assertEqual(expected, actual) def test_min_property_works_as_expected(self): expected = 1.5 item = RemoteDependencyData() item.min = expected actual = item.min self.assertEqual(expected, actual) expected = 4.8 item.min = expected actual = item.min self.assertEqual(expected, actual) def test_max_property_works_as_expected(self): expected = 1.5 item = RemoteDependencyData() item.max = expected actual = item.max self.assertEqual(expected, actual) expected = 4.8 item.max = expected actual = item.max self.assertEqual(expected, actual) def test_std_dev_property_works_as_expected(self): expected = 1.5 item = RemoteDependencyData() item.std_dev = expected actual = item.std_dev self.assertEqual(expected, actual) expected = 4.8 item.std_dev = expected actual = item.std_dev self.assertEqual(expected, actual) def test_dependency_kind_property_works_as_expected(self): expected = object() item = RemoteDependencyData() item.dependency_kind = expected actual = item.dependency_kind self.assertEqual(expected, actual) expected = object() item.dependency_kind = expected actual = item.dependency_kind self.assertEqual(expected, actual) def test_success_property_works_as_expected(self): expected = True item = RemoteDependencyData() item.success = expected actual = item.success self.assertEqual(expected, actual) expected = False item.success = expected actual = item.success self.assertEqual(expected, actual) def test_async_property_works_as_expected(self): expected = True item = RemoteDependencyData() item.async = expected actual = item.async self.assertEqual(expected, actual) expected = False item.async = expected actual = item.async self.assertEqual(expected, actual) def test_dependency_source_property_works_as_expected(self): expected = object() item = RemoteDependencyData() item.dependency_source = expected actual = item.dependency_source self.assertEqual(expected, actual) expected = object() item.dependency_source = expected actual = item.dependency_source self.assertEqual(expected, actual) def test_properties_property_works_as_expected(self): item = RemoteDependencyData() actual = item.properties self.assertNotEqual(actual, None) def test_serialize_works_as_expected(self): item = RemoteDependencyData() item.ver = 42 item.name = 'Test string' item.kind = object() item.value = 1.5 item.count = 42 item.min = 1.5 item.max = 1.5 item.std_dev = 1.5 item.dependency_kind = object() item.success = True item.async = True item.dependency_source = object() for key, value in { 'key1': 'test value 1' , 'key2': 'test value 2' }.items(): item.properties[key] = value actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ver":42,"name":"Test string","kind":{},"value":1.5,"count":42,"min":1.5,"max":1.5,"stdDev":1.5,"dependencyKind":{},"success":true,"async":true,"dependencySource":{},"properties":{"key1":"test value 1","key2":"test value 2"}}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000015400000000000011215 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestRequestData.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestRequest0000644000076600000240000001204013143420775035016 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestRequestData(unittest.TestCase): def test_construct(self): item = RequestData() self.assertNotEqual(item, None) def test_ver_property_works_as_expected(self): expected = 42 item = RequestData() item.ver = expected actual = item.ver self.assertEqual(expected, actual) expected = 13 item.ver = expected actual = item.ver self.assertEqual(expected, actual) def test_id_property_works_as_expected(self): expected = 'Test string' item = RequestData() item.id = expected actual = item.id self.assertEqual(expected, actual) expected = 'Other string' item.id = expected actual = item.id self.assertEqual(expected, actual) def test_name_property_works_as_expected(self): expected = 'Test string' item = RequestData() item.name = expected actual = item.name self.assertEqual(expected, actual) expected = 'Other string' item.name = expected actual = item.name self.assertEqual(expected, actual) def test_start_time_property_works_as_expected(self): expected = 'Test string' item = RequestData() item.start_time = expected actual = item.start_time self.assertEqual(expected, actual) expected = 'Other string' item.start_time = expected actual = item.start_time self.assertEqual(expected, actual) def test_duration_property_works_as_expected(self): expected = 'Test string' item = RequestData() item.duration = expected actual = item.duration self.assertEqual(expected, actual) expected = 'Other string' item.duration = expected actual = item.duration self.assertEqual(expected, actual) def test_response_code_property_works_as_expected(self): expected = 'Test string' item = RequestData() item.response_code = expected actual = item.response_code self.assertEqual(expected, actual) expected = 'Other string' item.response_code = expected actual = item.response_code self.assertEqual(expected, actual) def test_success_property_works_as_expected(self): expected = True item = RequestData() item.success = expected actual = item.success self.assertEqual(expected, actual) expected = False item.success = expected actual = item.success self.assertEqual(expected, actual) def test_http_method_property_works_as_expected(self): expected = 'Test string' item = RequestData() item.http_method = expected actual = item.http_method self.assertEqual(expected, actual) expected = 'Other string' item.http_method = expected actual = item.http_method self.assertEqual(expected, actual) def test_url_property_works_as_expected(self): expected = 'Test string' item = RequestData() item.url = expected actual = item.url self.assertEqual(expected, actual) expected = 'Other string' item.url = expected actual = item.url self.assertEqual(expected, actual) def test_properties_property_works_as_expected(self): item = RequestData() actual = item.properties self.assertNotEqual(actual, None) def test_measurements_property_works_as_expected(self): item = RequestData() actual = item.measurements self.assertNotEqual(actual, None) def test_serialize_works_as_expected(self): item = RequestData() item.ver = 42 item.id = 'Test string' item.name = 'Test string' item.start_time = 'Test string' item.duration = 'Test string' item.response_code = 'Test string' item.success = True item.http_method = 'Test string' item.url = 'Test string' for key, value in { 'key1': 'test value 1' , 'key2': 'test value 2' }.items(): item.properties[key] = value for key, value in { 'key1': 3.1415 , 'key2': 42.2 }.items(): item.measurements[key] = value actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ver":42,"id":"Test string","name":"Test string","startTime":"Test string","duration":"Test string","responseCode":"Test string","success":true,"httpMethod":"Test string","url":"Test string","properties":{"key1":"test value 1","key2":"test value 2"},"measurements":{"key1":3.1415,"key2":42.2}}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000015000000000000011211 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestSession.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestSession0000644000076600000240000000367413143420775035026 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestSession(unittest.TestCase): def test_construct(self): item = Session() self.assertNotEqual(item, None) def test_id_property_works_as_expected(self): expected = 'Test string' item = Session() item.id = expected actual = item.id self.assertEqual(expected, actual) expected = 'Other string' item.id = expected actual = item.id self.assertEqual(expected, actual) def test_is_first_property_works_as_expected(self): expected = 'Test string' item = Session() item.is_first = expected actual = item.is_first self.assertEqual(expected, actual) expected = 'Other string' item.is_first = expected actual = item.is_first self.assertEqual(expected, actual) def test_is_new_property_works_as_expected(self): expected = 'Test string' item = Session() item.is_new = expected actual = item.is_new self.assertEqual(expected, actual) expected = 'Other string' item.is_new = expected actual = item.is_new self.assertEqual(expected, actual) def test_serialize_works_as_expected(self): item = Session() item.id = 'Test string' item.is_first = 'Test string' item.is_new = 'Test string' actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ai.session.id":"Test string","ai.session.isFirst":"Test string","ai.session.isNew":"Test string"}' self.assertEqual(expected, actual) ././@LongLink0000000000000000000000000000015300000000000011214 Lustar 00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestStackFrame.pyapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestStackFr0000644000076600000240000000526613143420775034737 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestStackFrame(unittest.TestCase): def test_construct(self): item = StackFrame() self.assertNotEqual(item, None) def test_level_property_works_as_expected(self): expected = 42 item = StackFrame() item.level = expected actual = item.level self.assertEqual(expected, actual) expected = 13 item.level = expected actual = item.level self.assertEqual(expected, actual) def test_method_property_works_as_expected(self): expected = 'Test string' item = StackFrame() item.method = expected actual = item.method self.assertEqual(expected, actual) expected = 'Other string' item.method = expected actual = item.method self.assertEqual(expected, actual) def test_assembly_property_works_as_expected(self): expected = 'Test string' item = StackFrame() item.assembly = expected actual = item.assembly self.assertEqual(expected, actual) expected = 'Other string' item.assembly = expected actual = item.assembly self.assertEqual(expected, actual) def test_file_name_property_works_as_expected(self): expected = 'Test string' item = StackFrame() item.file_name = expected actual = item.file_name self.assertEqual(expected, actual) expected = 'Other string' item.file_name = expected actual = item.file_name self.assertEqual(expected, actual) def test_line_property_works_as_expected(self): expected = 42 item = StackFrame() item.line = expected actual = item.line self.assertEqual(expected, actual) expected = 13 item.line = expected actual = item.line self.assertEqual(expected, actual) def test_serialize_works_as_expected(self): item = StackFrame() item.level = 42 item.method = 'Test string' item.assembly = 'Test string' item.file_name = 'Test string' item.line = 42 actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"level":42,"method":"Test string","assembly":"Test string","fileName":"Test string","line":42}' self.assertEqual(expected, actual) applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/TestUser.py0000644000076600000240000000475413143420775034750 0ustar alexbstaff00000000000000import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestUser(unittest.TestCase): def test_construct(self): item = User() self.assertNotEqual(item, None) def test_account_acquisition_date_property_works_as_expected(self): expected = 'Test string' item = User() item.account_acquisition_date = expected actual = item.account_acquisition_date self.assertEqual(expected, actual) expected = 'Other string' item.account_acquisition_date = expected actual = item.account_acquisition_date self.assertEqual(expected, actual) def test_account_id_property_works_as_expected(self): expected = 'Test string' item = User() item.account_id = expected actual = item.account_id self.assertEqual(expected, actual) expected = 'Other string' item.account_id = expected actual = item.account_id self.assertEqual(expected, actual) def test_user_agent_property_works_as_expected(self): expected = 'Test string' item = User() item.user_agent = expected actual = item.user_agent self.assertEqual(expected, actual) expected = 'Other string' item.user_agent = expected actual = item.user_agent self.assertEqual(expected, actual) def test_id_property_works_as_expected(self): expected = 'Test string' item = User() item.id = expected actual = item.id self.assertEqual(expected, actual) expected = 'Other string' item.id = expected actual = item.id self.assertEqual(expected, actual) def test_serialize_works_as_expected(self): item = User() item.account_acquisition_date = 'Test string' item.account_id = 'Test string' item.user_agent = 'Test string' item.id = 'Test string' actual = json.dumps(item.write(), separators=(',', ':'), cls=TestJsonEncoder) expected = '{"ai.user.accountAcquisitionDate":"Test string","ai.user.accountId":"Test string","ai.user.userAgent":"Test string","ai.user.id":"Test string"}' self.assertEqual(expected, actual) applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/contracts_tests/Utils.py0000644000076600000240000000032413143420775034257 0ustar alexbstaff00000000000000import json class TestJsonEncoder(json.JSONEncoder): def default(self, obj): if obj and obj.__class__.__name__ == 'object': return {} return json.JSONEncoder.default(self, obj)applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/TestAsynchronousQueue.py0000644000076600000240000000373113143420775034302 0ustar alexbstaff00000000000000import unittest import sys, os, os.path rootDirectory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..') if rootDirectory not in sys.path: sys.path.append(rootDirectory) from applicationinsights import channel class TestAsynchronousQueue(unittest.TestCase): def test_construct(self): queue = channel.AsynchronousQueue(MockAsynchronousSender()) self.assertIsNotNone(queue.flush_notification) def test_flush_notification_works_as_expected(self): queue = channel.AsynchronousQueue(MockAsynchronousSender()) self.assertIsNotNone(queue.flush_notification) result = queue.flush_notification.wait(1) self.assertEqual(False, result) queue.flush_notification.set() result = queue.flush_notification.wait() self.assertEqual(True, result) queue.flush_notification.clear() result = queue.flush_notification.wait(1) self.assertEqual(False, result) def test_push_works_As_expected(self): sender = MockAsynchronousSender() queue = channel.AsynchronousQueue(sender) queue.put(42) self.assertEqual(1, sender.start_call_count) self.assertEqual(42, queue.get()) self.assertIsNone(queue.get()) def test_flush_works_as_expected(self): sender = MockAsynchronousSender() queue = channel.AsynchronousQueue(sender) self.assertIsNotNone(queue.flush_notification) result = queue.flush_notification.wait(1) self.assertEqual(False, result) queue.flush() self.assertEqual(1, sender.start_call_count) result = queue.flush_notification.wait() self.assertEqual(True, result) class MockAsynchronousSender: def __init__(self): self.send_buffer_size = 2 self.data = [] self.queue = None self.start_call_count = 0 def start(self): self.start_call_count += 1 def send(self, data_to_send): self.data.append(data_to_send) applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/TestAsynchronousSender.py0000644000076600000240000000472013143420775034435 0ustar alexbstaff00000000000000import unittest import time import sys, os, os.path rootDirectory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..') if rootDirectory not in sys.path: sys.path.append(rootDirectory) from applicationinsights import channel class TestAsynchronousSender(unittest.TestCase): def test_construct(self): sender = channel.AsynchronousSender() self.assertEqual('https://dc.services.visualstudio.com/v2/track', sender.service_endpoint_uri) self.assertEqual(1.0, sender.send_interval) self.assertEqual(3.0, sender.send_time) def test_send_interval_works_as_expected(self): sender = channel.AsynchronousSender() self.assertEqual(1.0, sender.send_interval) sender.send_interval = 10.0 self.assertEqual(10.0, sender.send_interval) def test_send_time_works_as_expected(self): sender = channel.AsynchronousSender() self.assertEqual(3.0, sender.send_time) sender.send_time = 10.0 self.assertEqual(10.0, sender.send_time) def test_start(self): sender = InterceptableAsynchronousSender() sender.send_interval = 1.0 sender.send_time = 3.0 queue = InterceptableAsynchronousQueue(sender) sender.invoke_base_start = False queue.put(1) queue.put(2) sender.invoke_base_start = True sender.start() time.sleep(2.0 * sender.send_time / 3.0) queue.put(3) time.sleep((1.0 * sender.send_time / 3.0) + 2.0) data = sender.data_to_send if [[1, 2], [3]] != data and [[1, 2]] != data: self.fail('Invalid result') get_calls = queue.get_calls if 10 != len(get_calls) and 6 != len(get_calls): self.fail('Invalid count') class InterceptableAsynchronousQueue(channel.AsynchronousQueue): def __init__(self, sender): self.get_calls = [] channel.AsynchronousQueue.__init__(self, sender) def get(self): output = channel.AsynchronousQueue.get(self) self.get_calls.append((time.gmtime(), output)) return output class InterceptableAsynchronousSender(channel.AsynchronousSender): def __init__(self): self.data_to_send = [] self.invoke_base_start = False channel.AsynchronousSender.__init__(self) def start(self): if self.invoke_base_start: channel.AsynchronousSender.start(self) def send(self, data_to_send): self.data_to_send.append(data_to_send)applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/TestQueueBase.py0000644000076600000240000000366713143420775032471 0ustar alexbstaff00000000000000import unittest import sys, os, os.path rootDirectory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..') if rootDirectory not in sys.path: sys.path.append(rootDirectory) from applicationinsights import channel class TestQueueBase(unittest.TestCase): def test_construct(self): sender = MockQueueBaseSender() actual = channel.QueueBase(sender) self.assertIsNotNone(actual) self.assertEqual(500, actual.max_queue_length) self.assertEqual(sender, actual.sender) self.assertEqual(actual, sender.queue) def test_max_queue_length_works_as_expected(self): actual = channel.QueueBase(None) self.assertEqual(500, actual.max_queue_length) actual.max_queue_length = 1000 self.assertEqual(1000, actual.max_queue_length) actual.max_queue_length = -1 self.assertEqual(1, actual.max_queue_length) def test_sender_works_as_expected(self): sender = MockQueueBaseSender() actual = channel.QueueBase(sender) self.assertEqual(sender, actual.sender) def test_put_works_as_expected(self): actual = InterceptableQueueBase(None) actual.max_queue_length = 1 actual.put(None) actual.put(1) actual.put(2) self.assertEqual(1, actual.get()) self.assertEqual(2, actual.get()) self.assertEqual(None, actual.get()) self.assertEqual(None, actual.get()) self.assertEqual(2, actual.flush_count) def test_get_works_as_expected(self): self.test_put_works_as_expected() def test_flush_works_as_expected(self): self.test_put_works_as_expected() class InterceptableQueueBase(channel.QueueBase): def __init__(self, sender): channel.QueueBase.__init__(self, sender) self.flush_count = 0 def flush(self): self.flush_count += 1 class MockQueueBaseSender(object): def __init__(self): self.queue = Noneapplicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/TestSenderBase.py0000644000076600000240000000763613143420775032625 0ustar alexbstaff00000000000000import random import unittest import time import threading try: # Python 2.x import BaseHTTPServer as HTTPServer except ImportError: # Python 3.x import http.server as HTTPServer import sys, os, os.path rootDirectory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..') if rootDirectory not in sys.path: sys.path.append(rootDirectory) from applicationinsights import channel class TestSenderBase(unittest.TestCase): def test_construct(self): actual = channel.SenderBase('http://tempuri.org/') self.assertIsNotNone(actual) self.assertEqual('http://tempuri.org/', actual.service_endpoint_uri) self.assertIsNone(actual.queue) self.assertEqual(100, actual.send_buffer_size) def test_service_endpoint_uri_works_as_expected(self): actual = channel.SenderBase('http://tempuri.org/') self.assertEqual('http://tempuri.org/', actual.service_endpoint_uri) actual.service_endpoint_uri = 'foo' self.assertEqual('foo', actual.service_endpoint_uri) def test_queue_works_as_expected(self): actual = channel.SenderBase('http://tempuri.org/') self.assertIsNone(actual.queue) expected = object() actual.queue = expected self.assertEqual(expected, actual.queue) def test_send_buffer_size_works_as_expected(self): actual = channel.SenderBase('http://tempuri.org/') self.assertEqual(100, actual.send_buffer_size) actual.send_buffer_size = 42 self.assertEqual(42, actual.send_buffer_size) actual.send_buffer_size = -1 self.assertEqual(1, actual.send_buffer_size) def test_send_works_as_expected(self): port = random.randint(50000, 60000) actual = channel.SenderBase("http://localhost:" + str(port) + "/track") actual.queue = channel.QueueBase(None) MockHTTPRequestHandler.ExpectedContent = "[42, 13]" MockHTTPRequestHandler.TestCase = self # save a reference to the test case in our handler thread = WorkerThread(actual) thread.start() runHttpHandlerOnce(handler=MockHTTPRequestHandler, port=port) # run the HTTP request thread.join() if "failed" in dir(self): self.fail(self.failed) self.assertEqual(None, actual.queue.get()) class WorkerThread(threading.Thread): def __init__(self, sender): threading.Thread.__init__(self) self.sender = sender def run(self): time.sleep(1) self.sender.send([ MockSerializable(42), MockSerializable(13) ]) class MockSerializable(object): def __init__(self, data): self._data = data def write(self): return self._data class MockHTTPRequestHandler(HTTPServer.BaseHTTPRequestHandler): ExpectedContent = None TestCase = None def do_POST(self): contentLength = int(self.headers['Content-Length']) content = self.rfile.read(contentLength) response = "" if isinstance(content, bytes): content = content.decode("utf-8") response = b"" if "POST" != self.command: MockHTTPRequestHandler.TestCase.failed = '"POST" != self.command' if "application/json; charset=utf-8" != self.headers["Content-Type"]: MockHTTPRequestHandler.TestCase.failed = '"application/json; charset=utf-8" != self.headers.type' if MockHTTPRequestHandler.ExpectedContent != content: MockHTTPRequestHandler.TestCase.failed = '"' + MockHTTPRequestHandler.ExpectedContent + '" != content' self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", "0") self.end_headers() self.wfile.write(response) def runHttpHandlerOnce(server=HTTPServer.HTTPServer, handler=HTTPServer.BaseHTTPRequestHandler, port=8121): serverAddress = ('', port) httpd = server(serverAddress, handler) httpd.handle_request()applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/TestSynchronousQueue.py0000644000076600000240000000204413143420775034135 0ustar alexbstaff00000000000000import unittest import sys, os, os.path rootDirectory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..') if rootDirectory not in sys.path: sys.path.append(rootDirectory) from applicationinsights import channel class TestSynchronousQueue(unittest.TestCase): def test_construct(self): actual = channel.SynchronousQueue(MockSynchronousSender()) self.assertIsNotNone(actual) def test_flush_works_as_expected(self): sender = MockSynchronousSender() queue = channel.SynchronousQueue(sender) queue.max_queue_length = 3 for i in range(1, 8): queue.put(i) self.assertEqual([[1, 2], [3], [4, 5], [6]], sender.data) temp = [] while queue._queue.qsize() > 0: temp.append(queue._queue.get()) self.assertEqual([7], temp) class MockSynchronousSender: def __init__(self): self.send_buffer_size = 2 self.data = [] self.queue = None def send(self, data_to_send): self.data.append(data_to_send) applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/TestSynchronousSender.py0000644000076600000240000000072013143420775034270 0ustar alexbstaff00000000000000import unittest import sys, os, os.path rootDirectory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..') if rootDirectory not in sys.path: sys.path.append(rootDirectory) from applicationinsights import channel class TestSynchronousSender(unittest.TestCase): def test_construct(self): sender = channel.SynchronousSender() self.assertEqual('https://dc.services.visualstudio.com/v2/track', sender.service_endpoint_uri) applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/TestTelemetryChannel.py0000644000076600000240000001245013143420775034043 0ustar alexbstaff00000000000000import unittest import sys, os, os.path rootDirectory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..') if rootDirectory not in sys.path: sys.path.append(rootDirectory) from applicationinsights import channel class TestTelemetryChannel(unittest.TestCase): def test_construct(self): actual = channel.TelemetryChannel() self.assertIsNotNone(actual) def test_context_works_as_expected(self): context_global = channel.TelemetryContext() context_global.device.id = "global" actual = channel.TelemetryChannel() self.assertIsNotNone(actual.context) actual = channel.TelemetryChannel(None) self.assertIsNotNone(actual.context) actual = channel.TelemetryChannel(context_global) self.assertEqual(context_global, actual.context) def test_queue_works_as_expected(self): queue = object() actual = channel.TelemetryChannel() self.assertIsNotNone(actual.queue) actual = channel.TelemetryChannel(None, None) self.assertIsNotNone(actual.queue) actual = channel.TelemetryChannel(None, queue) self.assertEqual(queue, actual.queue) def test_sender_works_as_expected(self): actual = channel.TelemetryChannel() self.assertIsNotNone(actual.sender) def test_flush_works_as_expected(self): queue = MockQueue() actual = channel.TelemetryChannel(None, queue) self.assertEqual(0, queue.flush_count) actual.flush() self.assertEqual(1, queue.flush_count) def test_construct_with_context_and_sender(self): mock_sender = MockTelemetrySender() queue = channel.SynchronousQueue(mock_sender) context_global = channel.TelemetryContext() context_global.device.id = "global" actual = channel.TelemetryChannel(context_global, queue) actual.write(channel.contracts.MessageData()) actual.flush() self.assertIsNotNone(mock_sender.data) self.assertEqual("global", mock_sender.data.tags["ai.device.id"]) def test_write_with_no_data_raises_exception(self): mock_sender = MockTelemetrySender() queue = channel.SynchronousQueue(mock_sender) actual = channel.TelemetryChannel(None, queue) self.assertRaises(Exception, actual.write, None) def test_write_transfers_local_convext_over_global_context(self): mock_sender = MockTelemetrySender() queue = channel.SynchronousQueue(mock_sender) context_global = channel.TelemetryContext() context_global.device.id = "global" context_local = channel.TelemetryContext() context_local.device.id = "local" actual = channel.TelemetryChannel(context_global, queue) actual.write(channel.contracts.MessageData(), context_local) actual.flush() self.assertIsNotNone(mock_sender.data) self.assertEqual("local", mock_sender.data.tags["ai.device.id"]) def test_write_constructs_valid_envelope(self): mock_sender = MockTelemetrySender() queue = channel.SynchronousQueue(mock_sender) context_global = channel.TelemetryContext() context_global.instrumentation_key = "42" actual = channel.TelemetryChannel(context_global, queue) cases = [ channel.contracts.EventData(), channel.contracts.MetricData(), channel.contracts.MessageData(), channel.contracts.PageViewData(), channel.contracts.ExceptionData(), ] for item in cases: actual.write(item) actual.flush() self.assertIsNotNone(mock_sender.data) self.assertTrue(isinstance(mock_sender.data, channel.contracts.Envelope)) self.assertEqual(item.ENVELOPE_TYPE_NAME, mock_sender.data.name) self.assertIsNotNone(mock_sender.data.time) self.assertEqual("42", mock_sender.data.ikey) for key, value in context_global.device.write().items(): self.assertEqual(value, mock_sender.data.tags[key]) for key, value in context_global.application.write().items(): self.assertEqual(value, mock_sender.data.tags[key]) for key, value in context_global.user.write().items(): self.assertEqual(value, mock_sender.data.tags[key]) for key, value in context_global.session.write().items(): self.assertEqual(value, mock_sender.data.tags[key]) for key, value in context_global.location.write().items(): self.assertEqual(value, mock_sender.data.tags[key]) for key, value in context_global.operation.write().items(): self.assertEqual(value, mock_sender.data.tags[key]) self.assertIsNotNone(mock_sender.data.data) self.assertEqual(item.DATA_TYPE_NAME, mock_sender.data.data.base_type) self.assertEqual(item, mock_sender.data.data.base_data) class MockQueue(object): def __init__(self): self.flush_count = 0 def flush(self): self.flush_count += 1 class MockTelemetrySender(channel.TelemetryChannel().sender.__class__): def __init__(self): self.data = None self.send_buffer_size = 1 def send(self, envelope): self.data = envelope[0]; applicationinsights-0.11.0/tests/applicationinsights_tests/channel_tests/TestTelemetryContext.py0000644000076600000240000001120013143420775034107 0ustar alexbstaff00000000000000import unittest import platform import locale import sys, os, os.path rootDirectory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..') if rootDirectory not in sys.path: sys.path.append(rootDirectory) from applicationinsights import channel class TestTelemetryContext(unittest.TestCase): def test_construct(self): context = channel.TelemetryContext() self.assertIsNone(context.instrumentation_key) self.assertIsNotNone(context.device) self.assertEqual("Other", context.device.type) self.assertEqual(platform.node(), context.device.id) self.assertEqual(platform.version(), context.device.os_version) self.assertEqual(locale.getdefaultlocale()[0], context.device.locale) self.assertIsNotNone(context.application) self.assertIsNotNone(context.user) self.assertIsNotNone(context.session) self.assertIsNotNone(context.operation) self.assertIsNotNone(context.location) self.assertIsNotNone(context.properties) def test_instrumentation_key_attribute_works_as_expected(self): context = channel.TelemetryContext() self.assertIsNone(context.instrumentation_key) context.instrumentation_key = "foo" self.assertEqual("foo", context.instrumentation_key) def test_device_attribute_works_as_expected(self): context = channel.TelemetryContext() self.assertIsNotNone(context.device) context.device = None self.assertIsNone(context.device) context.device = Exception() self.assertIsNotNone(context.device) self.assertIsInstance(context.device, Exception) context.device = channel.contracts.Device() self.assertIsNotNone(context.device) self.assertIsInstance(context.device, channel.contracts.Device) def test_application_attribute_works_as_expected(self): context = channel.TelemetryContext() self.assertIsNotNone(context.application) context.application = None self.assertIsNone(context.application) context.application = Exception() self.assertIsNotNone(context.application) self.assertIsInstance(context.application, Exception) context.application = channel.contracts.Application() self.assertIsNotNone(context.application) self.assertIsInstance(context.application, channel.contracts.Application) def test_user_attribute_works_as_expected(self): context = channel.TelemetryContext() self.assertIsNotNone(context.user) context.user = None self.assertIsNone(context.user) context.user = Exception() self.assertIsNotNone(context.user) self.assertIsInstance(context.user, Exception) context.user = channel.contracts.User() self.assertIsNotNone(context.user) self.assertIsInstance(context.user, channel.contracts.User) def test_session_attribute_works_as_expected(self): context = channel.TelemetryContext() self.assertIsNotNone(context.session) context.session = None self.assertIsNone(context.session) context.session = Exception() self.assertIsNotNone(context.session) self.assertIsInstance(context.session, Exception) context.session = channel.contracts.Session() self.assertIsNotNone(context.session) self.assertIsInstance(context.session, channel.contracts.Session) def test_location_attribute_works_as_expected(self): context = channel.TelemetryContext() self.assertIsNotNone(context.location) context.location = None self.assertIsNone(context.location) context.location = Exception() self.assertIsNotNone(context.location) self.assertIsInstance(context.location, Exception) context.location = channel.contracts.Location() self.assertIsNotNone(context.location) self.assertIsInstance(context.location, channel.contracts.Location) def test_operation_attribute_works_as_expected(self): context = channel.TelemetryContext() self.assertIsNotNone(context.operation) context.operation = None self.assertIsNone(context.operation) context.operation = Exception() self.assertIsNotNone(context.operation) self.assertIsInstance(context.operation, Exception) context.operation = channel.contracts.Operation() self.assertIsNotNone(context.operation) self.assertIsInstance(context.operation, channel.contracts.Operation) def test_properties_property_works_as_expected(self): context = channel.TelemetryContext() self.assertIsNotNone(context.properties) applicationinsights-0.11.0/tests/applicationinsights_tests/exception_tests/0000755000076600000240000000000013145103565027747 5ustar alexbstaff00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/exception_tests/__init__.py0000644000076600000240000000003013143420775032054 0ustar alexbstaff00000000000000from . import TestEnableapplicationinsights-0.11.0/tests/applicationinsights_tests/exception_tests/TestEnable.py0000644000076600000240000000247613143420775032363 0ustar alexbstaff00000000000000import unittest import sys, os, os.path rootDirectory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..') if rootDirectory not in sys.path: sys.path.append(rootDirectory) from applicationinsights import channel, exceptions class TestEnable(unittest.TestCase): def test_enable(self): original = sys.excepthook sys.excepthook = mock_excepthook sender = MockSynchronousSender() queue = channel.SynchronousQueue(sender) telemetry_channel = channel.TelemetryChannel(None, queue) exceptions.enable('foo', telemetry_channel=telemetry_channel) try: raise Exception('Boom') except: sys.excepthook(*sys.exc_info()) sys.excepthook = original data = sender.data[0][0] self.assertIsNotNone(data) self.assertEqual('foo', data.ikey) self.assertEqual('Microsoft.ApplicationInsights.Exception', data.name) def test_enable_raises_exception_on_no_instrumentation_key(self): self.assertRaises(Exception, exceptions.enable, None) def mock_excepthook(type, value, tb): pass class MockSynchronousSender: def __init__(self): self.send_buffer_size = 1 self.data = [] self.queue = None def send(self, data_to_send): self.data.append(data_to_send)applicationinsights-0.11.0/tests/applicationinsights_tests/logging_tests/0000755000076600000240000000000013145103565027377 5ustar alexbstaff00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/logging_tests/__init__.py0000644000076600000240000000004013143420775031505 0ustar alexbstaff00000000000000from . import TestLoggingHandlerapplicationinsights-0.11.0/tests/applicationinsights_tests/logging_tests/TestLoggingHandler.py0000644000076600000240000001111613143421424033470 0ustar alexbstaff00000000000000import unittest import logging as pylogging import sys, os, os.path rootDirectory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..') if rootDirectory not in sys.path: sys.path.append(rootDirectory) from applicationinsights import logging class TestEnable(unittest.TestCase): def test_enable(self): handler1 = logging.enable('foo') self.assertIsNotNone(handler1) self.assertEqual('LoggingHandler', handler1.__class__.__name__) self.assertEqual('foo', handler1.client.context.instrumentation_key) handler2 = logging.enable('foo') self.assertEqual('LoggingHandler', handler2.__class__.__name__) self.assertEqual('foo', handler2.client.context.instrumentation_key) channel = MockChannel() handler3 = logging.enable('bar', telemetry_channel=channel) self.assertIsNotNone(handler1) self.assertEqual('LoggingHandler', handler3.__class__.__name__) self.assertEqual('bar', handler3.client.context.instrumentation_key) self.assertEqual(channel, handler3.client.channel) all_handlers = pylogging.getLogger().handlers self.assertIn(handler2, all_handlers) self.assertIn(handler3, all_handlers) pylogging.getLogger().removeHandler(handler2) pylogging.getLogger().removeHandler(handler3) def test_enable_raises_exception_on_no_instrumentation_key(self): self.assertRaises(Exception, logging.enable, None) class TestLoggingHandler(unittest.TestCase): def test_construct(self): handler = logging.LoggingHandler('test') self.assertIsNotNone(handler) self.assertEqual('test', handler.client.context.instrumentation_key) def test_construct_raises_exception_on_no_instrumentation_key(self): self.assertRaises(Exception, logging.LoggingHandler, None) def test_log_works_as_expected(self): logger, sender = self._setup_logger() expected = [ (logger.debug, 'debug message', 'Microsoft.ApplicationInsights.Message', 'test', 'MessageData', 0, 'simple_logger - DEBUG - debug message'), (logger.info, 'info message', 'Microsoft.ApplicationInsights.Message', 'test', 'MessageData', 1, 'simple_logger - INFO - info message'), (logger.warn, 'warn message', 'Microsoft.ApplicationInsights.Message', 'test', 'MessageData', 2, 'simple_logger - WARNING - warn message'), (logger.error, 'error message', 'Microsoft.ApplicationInsights.Message', 'test', 'MessageData', 3, 'simple_logger - ERROR - error message'), (logger.critical, 'critical message', 'Microsoft.ApplicationInsights.Message', 'test', 'MessageData', 4, 'simple_logger - CRITICAL - critical message') ] for logging_function, logging_parameter, envelope_type, ikey, data_type, severity_level, message in expected: logging_function(logging_parameter) data = sender.data[0][0] sender.data = [] self.assertEqual(envelope_type, data.name) self.assertEqual(ikey, data.ikey) self.assertEqual(data_type, data.data.base_type) self.assertEqual(message, data.data.base_data.message) self.assertEqual(severity_level, data.data.base_data.severity_level) def test_log_exception_works_as_expected(self): logger, sender = self._setup_logger() try: raise Exception('blah') except: logger.exception('some error') data = sender.data[0][0] self.assertEqual('Microsoft.ApplicationInsights.Exception', data.name) self.assertEqual('test', data.ikey) self.assertEqual('ExceptionData', data.data.base_type) self.assertEqual('blah', data.data.base_data.exceptions[0].message) def _setup_logger(self): logger = pylogging.getLogger('simple_logger') logger.setLevel(pylogging.DEBUG) handler = logging.LoggingHandler('test') handler.setLevel(pylogging.DEBUG) # mock out the sender sender = MockSynchronousSender() queue = handler.client.channel.queue queue.max_queue_length = 1 queue._sender = sender sender.queue = queue formatter = pylogging.Formatter('%(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) return logger, sender class MockChannel: def flush(self): pass class MockSynchronousSender: def __init__(self): self.send_buffer_size = 1 self.data = [] self.queue = None def send(self, data_to_send): self.data.append(data_to_send) applicationinsights-0.11.0/tests/applicationinsights_tests/requests_tests/0000755000076600000240000000000013145103565027624 5ustar alexbstaff00000000000000applicationinsights-0.11.0/tests/applicationinsights_tests/requests_tests/__init__.py0000644000076600000240000000004213143420775031734 0ustar alexbstaff00000000000000from . import TestWSGIApplication applicationinsights-0.11.0/tests/applicationinsights_tests/requests_tests/TestWSGIApplication.py0000644000076600000240000000702513143420775034002 0ustar alexbstaff00000000000000import unittest import wsgiref import sys, os, os.path rootDirectory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..') if rootDirectory not in sys.path: sys.path.append(rootDirectory) from applicationinsights import requests class TestWSGIApplication(unittest.TestCase): def test_construct(self): app = mock_app wrapper = requests.WSGIApplication('foo', app) self.assertIsNotNone(wrapper) self.assertIsNotNone(wrapper.client) self.assertEqual('foo', wrapper.client.context.instrumentation_key) def test_construct_raises_exception_on_no_instrumentation_key(self): self.assertRaises(Exception, requests.WSGIApplication, None, object()) def test_construct_raises_exception_on_no_wsgi_application(self): self.assertRaises(Exception, requests.WSGIApplication, 'foo', None) def test_wsgi_works_as_expected(self): app = mock_app wrapper = requests.WSGIApplication('test', app) sender = self._intercept_sender(wrapper) env = { 'REQUEST_METHOD': 'PUT', 'PATH_INFO': '/foo/bar', 'QUERY_STRING': 'a=b' } result = wrapper(env, mock_start_response) result_string = None for part in result: result_string = part data = sender.data[0][0] self.assertEqual('Microsoft.ApplicationInsights.Request', data.name) self.assertEqual('test', data.ikey) self.assertEqual('RequestData', data.data.base_type) self.assertEqual('PUT', data.data.base_data.http_method) self.assertEqual('/foo/bar', data.data.base_data.name) self.assertEqual('201', data.data.base_data.response_code) self.assertTrue(data.data.base_data.success) self.assertEqual('http://unknown/foo/bar?a=b', data.data.base_data.url) self.assertIsNotNone(data.data.base_data.id) self.assertEqual(b'Hello World!', result_string) self.assertEqual(1, mock_start_response_calls) self.assertEqual('201 BLAH', mock_start_response_status) self.assertEqual([('Content-type', 'text/plain')], mock_start_response_headers) def _intercept_sender(self, wsgi_application): client = wsgi_application.client # mock out the sender sender = MockAsynchronousSender() queue = client.channel.queue queue.max_queue_length = 1 queue._sender = sender sender.queue = queue return sender mock_start_response_calls = 0 mock_start_response_status = None mock_start_response_headers = None def mock_start_response(status, headers, exc_info=None): global mock_start_response_calls global mock_start_response_status global mock_start_response_headers mock_start_response_calls += 1 mock_start_response_status = status mock_start_response_headers = headers def mock_app(environ, start_response): status = '201 BLAH' headers = [('Content-type', 'text/plain')] start_response(status, headers) return [b'Hello World!'] class MockAsynchronousSender: def __init__(self): self.send_buffer_size = 1 self.data = [] self.queue = None def start(self): while True: data = [] while len(data) < self.send_buffer_size: item = self.queue.get() if not item: break data.append(item) if len(data) == 0: break self.send(data) def send(self, data_to_send): self.data.append(data_to_send)applicationinsights-0.11.0/tests/applicationinsights_tests/TestTelemetryClient.py0000644000076600000240000002335613143421424031056 0ustar alexbstaff00000000000000import unittest import inspect import json from test import test_support import sys, os, os.path rootDirectory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..') if rootDirectory not in sys.path: sys.path.append(rootDirectory) from applicationinsights import TelemetryClient, channel class TestTelemetryClient(unittest.TestCase): def test_constructor_throws_with_no_instrumentation_key(self): self.assertRaises(Exception, TelemetryClient, None) def test_constructor_sets_instrumentation_key(self): client = TelemetryClient('foo') self.assertEqual('foo', client.context.instrumentation_key) def test_constructor_maintains_backwards_compatibility_when_specifying_only_telemetry_channel(self): expected = channel.TelemetryChannel() client = TelemetryClient(expected) self.assertEqual(expected, client.channel) self.assertIsNone(client.context.instrumentation_key) def test_context_property_works_as_expected(self): client = TelemetryClient('foo') self.assertIsNotNone(client.context) def test_channel_property_works_as_expected(self): expected = channel.TelemetryChannel() client = TelemetryClient('foo', expected) self.assertEqual(expected, client.channel) def test_track_event_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 client.track_event('test', { 'foo': 'bar' }, { 'x': 42 }) client.flush() 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", "properties": {"foo": "bar"}, "measurements": {"x": 42}}}}' sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' actual = json.dumps(sender.data.write()) self.maxDiff = None self.assertEqual(expected, actual) def test_track_metric_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 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.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER"}, "data": {"baseType": "MetricData", "baseData": {"ver": 2, "metrics": [{"name": "metric", "kind": 1, "value": 42, "count": 13, "min": 1, "max": 123, "stdDev": 111}], "properties": {"foo": "bar"}}}}' sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' actual = json.dumps(sender.data.write()) self.maxDiff = None self.assertEqual(expected, actual) def test_track_trace_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 client.track_trace('test', { 'foo': 'bar' }, severity='WARNING') client.flush() expected = '{"ver": 1, "name": "Microsoft.ApplicationInsights.Message", "time": "TIME_PLACEHOLDER", "sampleRate": 100.0, "iKey": "99999999-9999-9999-9999-999999999999", "tags": {"ai.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER"}, "data": {"baseType": "MessageData", "baseData": {"ver": 2, "message": "test", "severityLevel": 2, "properties": {"foo": "bar"}}}}' sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' actual = json.dumps(sender.data.write()) self.maxDiff = None self.assertEqual(expected, actual) def test_track_pageview_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 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.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER"}, "data": {"baseType": "PageViewData", "baseData": {"ver": 2, "url": "http://tempuri.org", "name": "test", "duration": 13, "properties": {"foo": "bar"}, "measurements": {"x": 42}}}}' sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' actual = json.dumps(sender.data.write()) self.maxDiff = None self.assertEqual(expected, actual) 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 test_track_request_works_as_expected(self): sender = MockTelemetrySender() queue = channel.SynchronousQueue(sender) client = TelemetryClient(channel.TelemetryChannel(context=None, queue=queue)) client.context.instrumentation_key = '99999999-9999-9999-9999-999999999999' client.context.device = None client.track_request('test', 'http://tempuri.org', True, 'START_TIME', 13, '42', 'OPTIONS', { 'foo': 'bar' }, { 'x': 42 }) client.flush() expected = '{"ver": 1, "name": "Microsoft.ApplicationInsights.Request", "time": "TIME_PLACEHOLDER", "sampleRate": 100.0, "iKey": "99999999-9999-9999-9999-999999999999", "tags": {"ai.internal.sdkVersion": "SDK_VERSION_PLACEHOLDER"}, "data": {"baseType": "RequestData", "baseData": {"ver": 2, "id": "ID_PLACEHOLDER", "name": "test", "startTime": "START_TIME", "duration": "00:00:00.013", "responseCode": "42", "success": true, "httpMethod": "OPTIONS", "url": "http://tempuri.org", "properties": {"foo": "bar"}, "measurements": {"x": 42}}}}' sender.data.time = 'TIME_PLACEHOLDER' sender.data.tags['ai.internal.sdkVersion'] = 'SDK_VERSION_PLACEHOLDER' sender.data.data.base_data.id = 'ID_PLACEHOLDER' actual = json.dumps(sender.data.write()) self.maxDiff = None self.assertEqual(expected, actual) class MockTelemetrySender(channel.TelemetryChannel().sender.__class__): def __init__(self): self.data = None self.send_buffer_size = 1 def send(self, envelope): self.data = envelope[0];