Пример #1
0
    def init_app(self, app):
        INTEGRATIONS = ['httplib', 'sqlalchemy', 'requests']

        export_LocalForwarder = trace_exporter.TraceExporter(
            # FIXME - Move to config
            service_name=os.getenv('SERVICE_NAME', 'python-service'),
            endpoint=os.getenv('OCAGENT_TRACE_EXPORTER_ENDPOINT'),
            transport=BackgroundThreadTransport)

        tracer = tracer_module.Tracer(exporter=export_LocalForwarder,
                                      propagator=TraceContextPropagator())
        config_integration.trace_integrations(INTEGRATIONS, tracer=tracer)

        # Hookup OpenCensus to Flask
        FlaskMiddleware(app=app, exporter=export_LocalForwarder)

        # Also hookup AppInsights for logging
        AppInsights(app)
Пример #2
0
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import flask

from opencensus.trace.exporters import stackdriver_exporter
from opencensus.trace.ext.flask.flask_middleware import FlaskMiddleware

app = flask.Flask(__name__)

# Enable tracing the requests
middleware = FlaskMiddleware(app)


@app.route('/')
def hello():
    return 'Hello world!'


if __name__ == '__main__':
    app.run(host='localhost', port=8080)
Пример #3
0
PROJECT = os.environ.get('GCLOUD_PROJECT_PYTHON')

# MySQL settings
MYSQL_PASSWORD = os.environ.get('SYSTEST_MYSQL_PASSWORD')

# PostgreSQL settings
POSTGRES_PASSWORD = os.environ.get('SYSTEST_POSTGRES_PASSWORD')

app = flask.Flask(__name__)

# Enable tracing, configure the trace params, send traces to Stackdriver Trace
exporter = stackdriver_exporter.StackdriverExporter(
    project_id='yanhuili-sandbox')
sampler = probability.ProbabilitySampler(rate=1)
middleware = FlaskMiddleware(app, exporter=exporter, sampler=sampler)
config_integration.trace_integrations(INTEGRATIONS)


@app.route('/')
def hello():
    return 'Hello world!'


@app.route('/requests')
def trace_requests():
    response = requests.get('http://www.google.com')
    return str(response.status_code)


@app.route('/mysql')
Пример #4
0
def create_app(config={}):
    app = Flask('aleph')
    app.config.from_object(settings)
    app.config.update(config)

    if 'postgres' not in settings.DATABASE_URI:
        raise RuntimeError("aleph database must be PostgreSQL!")

    app.config.update({
        'SQLALCHEMY_DATABASE_URI': settings.DATABASE_URI,
        'BABEL_DOMAIN': 'aleph'
    })

    queue = Queue(settings.QUEUE_NAME,
                  routing_key=settings.QUEUE_ROUTING_KEY,
                  queue_arguments={'x-max-priority': 9})
    celery.conf.update(
        imports=('aleph.queues'),
        broker_url=settings.BROKER_URI,
        task_always_eager=settings.EAGER,
        task_eager_propagates=True,
        task_ignore_result=True,
        task_acks_late=False,
        task_queues=(queue,),
        task_default_queue=settings.QUEUE_NAME,
        task_default_routing_key=settings.QUEUE_ROUTING_KEY,
        worker_max_tasks_per_child=1000,
        result_persistent=False,
        beat_schedule={
            'hourly': {
                'task': 'aleph.logic.scheduled.hourly',
                'schedule': crontab(hour='*', minute=0)
            },
            'daily': {
                'task': 'aleph.logic.scheduled.daily',
                'schedule': crontab(hour=5, minute=0)
            }
        },
    )

    migrate.init_app(app, db, directory=settings.ALEMBIC_DIR)
    configure_oauth(app)
    mail.init_app(app)
    db.init_app(app)
    babel.init_app(app)
    CORS(app, origins=settings.CORS_ORIGINS)

    # Enable raven to submit issues to sentry if a DSN is defined. This will
    # report errors from Flask and Celery operation modes to Sentry.
    if settings.SENTRY_DSN:
        sentry.init_app(app,
                        dsn=settings.SENTRY_DSN,
                        logging=True,
                        level=logging.ERROR)
        register_logger_signal(sentry.client)
        register_signal(sentry.client, ignore_expected=True)

    # This executes all registered init-time plugins so that other
    # applications can register their behaviour.
    for plugin in get_extensions('aleph.init'):
        plugin(app=app)
    # Set up opencensus tracing and its integrations. Export collected traces
    # to Stackdriver Trace on a background thread.
    if settings.STACKDRIVER_TRACE_PROJECT_ID:
        exporter = stackdriver_exporter.StackdriverExporter(
            project_id=settings.STACKDRIVER_TRACE_PROJECT_ID,
            transport=BackgroundThreadTransport
        )
        sampler = probability.ProbabilitySampler(
            rate=settings.TRACE_SAMPLING_RATE
        )
        blacklist_paths = ['/healthz', ]
        FlaskMiddleware(
            app, exporter=exporter, sampler=sampler,
            blacklist_paths=blacklist_paths
        )
        integrations = ['postgresql', 'sqlalchemy', 'httplib']
        config_integration.trace_integrations(integrations)
        # Set up logging
        setup_stackdriver_logging()
    return app
Пример #5
0
 def __init__(self, api_app):
     self.middleware = FlaskMiddleware(api_app)
Пример #6
0
# MySQL settings
MYSQL_PASSWORD = os.environ.get('SYSTEST_MYSQL_PASSWORD')

# PostgreSQL settings
POSTGRES_PASSWORD = os.environ.get('SYSTEST_POSTGRES_PASSWORD')

app = flask.Flask(__name__)

# Enable tracing, send traces to Stackdriver Trace using background thread transport.
# This is intentionally different from the Django system test which is using sync
# transport to test both.
from opencensus.trace.exporters.transports import background_thread
exporter = stackdriver_exporter.StackdriverExporter(
    transport=background_thread.BackgroundThreadTransport)

middleware = FlaskMiddleware(app, exporter=exporter)
config_integration.trace_integrations(INTEGRATIONS)


@app.route('/')
def hello():
    return 'hello'


@app.route('/mysql')
def mysql_query():
    try:
        conn = mysql.connector.connect(host=DB_HOST,
                                       user='******',
                                       password=MYSQL_PASSWORD)
        cursor = conn.cursor()
Пример #7
0
app = Flask(__name__)

topic_name = 'tracing-demo'

# Configure Tracing
exporter = stackdriver_exporter.StackdriverExporter(
    transport=background_thread.BackgroundThreadTransport)
propagator = google_cloud_format.GoogleCloudFormatPropagator()
sampler = always_on.AlwaysOnSampler()
blacklist_paths = ['favicon.ico']

# Instrument Flask to do tracing automatically
middleware = FlaskMiddleware(app,
                             exporter=exporter,
                             propagator=propagator,
                             sampler=sampler,
                             blacklist_paths=blacklist_paths)

# Create Pub/Sub client
# Messages sent with the HTTP request will be published to Cloud Pub/Sub
publisher = pubsub_v1.PublisherClient()
_, project_id = google.auth.default()
topic_path = publisher.topic_path(project_id, topic_name)


@app.route('/')
def template_test():
    """
    Handle the root path for this app. Renders a simple web page displaying a
    message. The default message is Hello World but this can be overridden by
Пример #8
0
import logging

# pylint: disable=invalid-name, broad-except

app = Flask(__name__.split('.')[0])
RequestID(app)

tracer = None
if opencensus_tracing_enabled():
    from opencensus.trace import config_integration
    from opencensus.trace.ext.flask.flask_middleware import FlaskMiddleware
    tracer = get_opencensus_tracer()
    integration = ['sqlalchemy']
    config_integration.trace_integrations(integration, tracer=tracer)
    jaegerExporter = get_jaeger_exporter()
    middleware = FlaskMiddleware(app, exporter=jaegerExporter)

handler = logging.StreamHandler()
handler.setFormatter(
    logging.Formatter(
        "[%(asctime)s] %(name)s [%(request_id)s] [%(levelname)s] %(message)s"))
handler.addFilter(RequestIDLogFilter())
_LOG = logging.getLogger()
_LOG.addHandler(handler)

# If invoked using Gunicorn, link our root logger to the gunicorn logger
# this will mean the root logs will be captured and managed by the gunicorn logger
# allowing you to set the gunicorn log directories and levels for logs
# produced by this application
_LOG.setLevel(logging.getLogger('gunicorn.error').getEffectiveLevel())
Пример #9
0
import sqlalchemy

from opencensus.trace.ext.flask.flask_middleware import FlaskMiddleware
from opencensus.trace import config_integration
from opencensus.trace.reporters import google_cloud_reporter

sys.path.insert(0, os.path.abspath(__file__ + "/../../../.."))
from ext import config

INTEGRATIONS = ['mysql', 'postgresql', 'sqlalchemy']

app = flask.Flask(__name__)

# Enbale tracing, send traces to Stackdriver Trace
reporter = google_cloud_reporter.GoogleCloudReporter()
middleware = FlaskMiddleware(app, reporter=reporter)
config_integration.trace_integrations(INTEGRATIONS)


@app.route('/')
def hello():
    return 'hello'


@app.route('/mysql')
def mysql_query():
    try:
        conn = mysql.connector.connect(user=config.MYSQL_USER,
                                       password=config.MYSQL_PASSWORD)
        cursor = conn.cursor()