コード例 #1
0
def _send_event(telemetry_uuid: str, event_name: str, event_data: dict) -> None:
    try:
        posthog.capture(telemetry_uuid, event_name, event_data)
    except APIError:
        raise AnalyticsServiceError(
            "PostHog experienced an error while capturing the event."
        )
コード例 #2
0
        def processor(event, hint):
            # type: (Event, Optional[Hint]) -> Optional[Event]
            if Hub.current.get_integration(PostHogIntegration) is not None:
                if event.get("level") != "error":
                    return event

                if event.get("tags", {}).get(POSTHOG_ID_TAG):
                    posthog_distinct_id = event["tags"][POSTHOG_ID_TAG]
                    event["tags"][
                        "PostHog URL"] = f"{posthog.host or DEFAULT_HOST}/person/{posthog_distinct_id}"

                    properties = {
                        "$sentry_event_id": event["event_id"],
                        "$sentry_exception": event["exception"],
                    }

                    if PostHogIntegration.organization:
                        project_id = PostHogIntegration.project_id or (
                            not not Hub.current.client.dsn
                            and Dsn(Hub.current.client.dsn).project_id)
                        if project_id:
                            properties[
                                "$sentry_url"] = f"{PostHogIntegration.prefix}{PostHogIntegration.organization}/issues/?project={project_id}&query={event['event_id']}"

                    posthog.capture(posthog_distinct_id, "$exception",
                                    properties)

            return event
コード例 #3
0
ファイル: simulator.py プロジェクト: PostHog/posthog-python
def capture():
    posthog.capture(
        options.distinct_id,
        options.event,
        anonymous_id=options.anonymousId,
        properties=json_hash(options.properties),
        context=json_hash(options.context),
    )
コード例 #4
0
def capture(event: str, properties: Optional[dict] = None) -> None:
    # Used for capturing generic events with properties
    if _NO_ANALYTICS:
        return None
    config = c.get_config()
    properties = properties or {}
    properties.update(source="cli")
    with suppress(Exception):
        posthog.capture(config.session_id, event, properties)
コード例 #5
0
ファイル: tracking.py プロジェクト: roman-pinchuk/zmanim_bot
        async def wrapper(*args, **kwargs):
            spec = inspect.getfullargspec(func)
            kwargs = {k: v for k, v in kwargs.items() if k in spec.args}

            user = User.get_current()
            msg = Message.get_current()
            attach_message_text and params.update({'text': msg.text})

            posthog.capture(user.id, action, params, message_id=msg.message_id)

            return await func(*args, **kwargs)
コード例 #6
0
ファイル: utils.py プロジェクト: rl-institut/E_Metrobus
def posthog_event(request, event=None):
    data = copy.deepcopy(request.session._session)
    data["session_id"] = request.session.session_key
    data["version"] = __version__
    if event is None:
        event = request.get_host() + request.path
    else:
        if event not in constants.POSTHOG_EVENTS:
            raise ValueError("Not a valid posthog event!")
        else:
            event = f"{request.get_host()}/{event}/"
    data["event"] = event
    posthog.capture(
        request.session.session_key,
        event,
        properties=data,
    )
コード例 #7
0
ファイル: analytics.py プロジェクト: sajanv88/orchest
def send_event(app, event, properties):
    if app.config["TELEMETRY_DISABLED"]:
        return False

    try:
        telemetry_uuid = get_telemetry_uuid(app)

        if "mode" not in properties:
            properties["mode"] = os.environ.get("FLASK_ENV", "production")

        properties["orchest_version"] = app.config["ORCHEST_REPO_TAG"]

        posthog.capture(telemetry_uuid, event, properties)
        app.logger.debug(
            "Sending event[%s] to Posthog for anonymized user [%s] with properties: %s"
            % (event, telemetry_uuid, properties))
        return True
    except (Exception, APIError) as e:
        app.logger.error("Could not send event through posthog %s" % e)
        return False
コード例 #8
0
ファイル: analytics.py プロジェクト: puqiu/orchest
def send_event(app, event, properties):
    if app.config["TELEMETRY_DISABLED"]:
        return False

    try:
        telemetry_uuid = get_telemetry_uuid(app)

        properties["dev"] = StaticConfig.FLASK_ENV == "development"
        properties["cloud"] = StaticConfig.CLOUD

        properties["orchest_version"] = app.config["ORCHEST_REPO_TAG"]

        posthog.capture(telemetry_uuid, event, properties)
        app.logger.debug(
            "Sending event[%s] to Posthog for anonymized user [%s] with properties: %s"
            % (event, telemetry_uuid, properties))
        return True
    except (Exception, APIError) as e:
        app.logger.error("Could not send event through posthog %s" % e)
        return False
コード例 #9
0
ファイル: module.py プロジェクト: magloirend/posthog-python
 def test_track(self):
     posthog.capture('distinct_id', 'python module event')
     posthog.flush()
コード例 #10
0
ファイル: example.py プロジェクト: PostHog/posthog-python
# Import the library
import time

import posthog

# You can find this key on the /setup page in PostHog
posthog.project_api_key = ""
posthog.personal_api_key = ""

# Where you host PostHog, with no trailing /.
# You can remove this line if you're using posthog.com
posthog.host = "http://127.0.0.1:8000"

# Capture an event
posthog.capture("distinct_id", "event", {
    "property1": "value",
    "property2": "value"
})

print(posthog.feature_enabled("beta-feature", "distinct_id"))
print(
    posthog.feature_enabled("beta-feature",
                            "distinct_id",
                            groups={"company": "id:5"}))

print("sleeping")
time.sleep(5)

print(posthog.feature_enabled("beta-feature", "distinct_id"))

# # Alias a previous distinct id with a new one
コード例 #11
0
ファイル: example.py プロジェクト: magloirend/posthog-python
# Import the library
import posthog
import time

# You can find this key on the /setup page in PostHog
posthog.api_key = ''
posthog.personal_api_key = ''

# Where you host PostHog, with no trailing /.
# You can remove this line if you're using posthog.com
posthog.host = 'http://127.0.0.1:8000'

# Capture an event
posthog.capture('distinct_id', 'event', {
    'property1': 'value',
    'property2': 'value'
})

print(posthog.feature_enabled('beta-feature', 'distinct_id'))

print('sleeping')
time.sleep(45)

print(posthog.feature_enabled('beta-feature', 'distinct_id'))

# # Alias a previous distinct id with a new one
posthog.alias('distinct_id', 'new_distinct_id')

# # Add properties to the person
posthog.identify('distinct_id', {'email': '*****@*****.**'})
コード例 #12
0
 async def handler(context):
     try:
         try:
             parameter = context.pattern_match.group(1).split(' ')
             if parameter == ['']:
                 parameter = []
             context.parameter = parameter
             context.arguments = context.pattern_match.group(1)
             posthog_capture = True
         except BaseException:
             posthog_capture = False
             context.parameter = None
             context.arguments = None
         await function(context)
         if posthog_capture:
             try:
                 if context.sender_id > 0 or context.sender_id == 1087968824:
                     posthog.capture(
                         str(context.sender_id), 'Function ' +
                         context.text.split()[0].replace('-', ''))
                 else:
                     me = await bot.get_me()
                     posthog.capture(
                         str(me.id), 'Function ' +
                         context.text.split()[0].replace('-', ''))
             except:
                 logs.info("上报命令使用状态出错了呜呜呜 ~。")
     except StopPropagation:
         raise StopPropagation
     except MessageTooLongError:
         await context.edit("出错了呜呜呜 ~ 生成的输出太长,无法显示。")
     except BaseException:
         exc_info = sys.exc_info()[1]
         exc_format = format_exc()
         try:
             await context.edit("出错了呜呜呜 ~ 执行此命令时发生错误。")
         except BaseException:
             pass
         if not diagnostics:
             return
         if strtobool(config['error_report']):
             report = f"# Generated: {strftime('%H:%M %d/%m/%Y', gmtime())}. \n" \
                      f"# ChatID: {str(context.chat_id)}. \n" \
                      f"# UserID: {str(context.sender_id)}. \n" \
                      f"# Message: \n-----BEGIN TARGET MESSAGE-----\n" \
                      f"{context.text}\n-----END TARGET MESSAGE-----\n" \
                      f"# Traceback: \n-----BEGIN TRACEBACK-----\n" \
                      f"{str(exc_format)}\n-----END TRACEBACK-----\n" \
                      f"# Error: \"{str(exc_info)}\". \n"
             await attach_report(report,
                                 f"exception.{time()}.pagermaid", None,
                                 "Error report generated.")
             try:
                 if context.sender_id > 0 or context.sender_id == 1087968824:
                     posthog.capture(
                         str(context.sender_id), 'Error ' +
                         context.text.split()[0].replace('-', ''), {
                             'ChatID': str(context.chat_id),
                             'cause': str(exc_info)
                         })
                 else:
                     me = await bot.get_me()
                     posthog.capture(
                         str(me.id), 'Error ' +
                         context.text.split()[0].replace('-', ''), {
                             'ChatID': str(context.chat_id),
                             'cause': str(exc_info)
                         })
             except:
                 logs.info("上报错误出错了呜呜呜 ~。")
コード例 #13
0
# Import the library
import time

import posthog

# You can find this key on the /setup page in PostHog
posthog.api_key = ""
posthog.personal_api_key = ""

# Where you host PostHog, with no trailing /.
# You can remove this line if you're using posthog.com
posthog.host = "http://127.0.0.1:8000"

# Capture an event
posthog.capture("distinct_id", "event", {
    "property1": "value",
    "property2": "value"
})

print(posthog.feature_enabled("beta-feature", "distinct_id"))

print("sleeping")
time.sleep(45)

print(posthog.feature_enabled("beta-feature", "distinct_id"))

# # Alias a previous distinct id with a new one
posthog.alias("distinct_id", "new_distinct_id")

# # Add properties to the person
posthog.identify("distinct_id", {"email": "*****@*****.**"})
コード例 #14
0
 def test_track(self):
     posthog.capture("distinct_id", "python module event")
     posthog.flush()
コード例 #15
0
def log_api(action,
            client_time=None,
            total_runtime=None,
            dag=None,
            metadata=None):
    """
    This function logs through an API call, assigns parameters if missing like
    timestamp, event id and stats information.
    """
    metadata = metadata or {}

    event_id = uuid.uuid4()
    if client_time is None:
        client_time = datetime.datetime.now()

    (telemetry_enabled, uid, is_install) = _get_telemetry_info()
    if 'NO_UID' in uid:
        metadata['uid_issue'] = uid
        uid = None

    py_version = python_version()
    docker_container = is_docker()
    colab = is_colab()
    if colab:
        metadata['colab'] = colab

    paperspace = is_paperspace()
    if paperspace:
        metadata['paperspace'] = paperspace

    slurm = is_slurm()
    if slurm:
        metadata['slurm'] = slurm

    airflow = is_airflow()
    if airflow:
        metadata['airflow'] = airflow

    argo = is_argo()
    if argo:
        metadata['argo'] = argo
    if dag:
        metadata['dag'] = parse_dag(dag)
    os = get_os()
    product_version = __version__
    online = is_online()
    environment = get_env()

    if telemetry_enabled and online:
        event_id, uid, action, client_time, elapsed_time \
            = validate_entries(event_id,
                               uid,
                               action,
                               client_time,
                               total_runtime)
        props = {
            'event_id': event_id,
            'user_id': uid,
            'action': action,
            'client_time': str(client_time),
            'metadata': metadata,
            'total_runtime': total_runtime,
            'python_version': py_version,
            'ploomber_version': product_version,
            'docker_container': docker_container,
            'os': os,
            'environment': environment,
            'metadata': metadata,
            'telemetry_version': TELEMETRY_VERSION
        }

        if is_install:
            posthog.capture(distinct_id=uid,
                            event='install_success_indirect',
                            properties=props)

        posthog.capture(distinct_id=uid, event=action, properties=props)