def result(section):
    """Accept a POST request and then respond to a GET request by showing some fixed json data to be forwarded to the EQ service. Both the POST and
    GET requests are handled by the URL http://localhost:8171/cases/<section>/events. The value of <section> will be the case UUID that corresponds
    to the IAC that the user enters."""
    PrintLogger().info("Now in the result function. Section is: " + section)
    my_case_stub = Case_Stub()
    data = Case_Stub.get_reponse_for_eq_stub(my_case_stub)
    data_as_json = json.dumps(data, separators=(',', ':'))
    PrintLogger().info("Now returning the response to forward to EQ")
    return Response(data_as_json, mimetype='application/json')
def show_case_data(section):
    """Show the fixed case json data that is produced by this case stub. The json data should be shown at the URL http://localhost:8171/cases/<section>
    The value of <section> will be the case UUID that corresponds to the IAC that the user enters. However the fixed json response will ignore
    the value of <section>, for the case UUID, and instead take the case UUID to be this fixed value: 0337c579-ce9d-4357-a620-5e4c565cfac1
    """
    PrintLogger().info("Now in the show_case_data function. Section is: " +
                       section)
    my_case_stub = Case_Stub()
    data = Case_Stub.get_case_stub(my_case_stub)
    PrintLogger().info("Data returned successfully")
    data_as_json = json.dumps(data, separators=(',', ':'))
    return Response(data_as_json, mimetype='application/json')
 def get_iac_stub(self, IacEntered):
     """Create the fixed iac response as a Python dictionary object. This can then be converted to a json object later on."""
     PrintLogger().info("Now in the get_iac_stub function")
     iac_fixed_response = {
         'caseId': '0337c579-ce9d-4357-a620-5e4c565cfac1',
         'caseRef': '1000000000000002',
         'iac': IacEntered,
         'active': True,
         'questionSet': None,
         'lastUsedDateTime': 1543502892050
     }
     PrintLogger().info("Now returning the iac fixed response: " +
                        repr(iac_fixed_response))
     return iac_fixed_response
Exemple #4
0
def show_iac_data(section):
    """Show the fixed IAC json data that is produced by this iac stub. The json data should be shown at the URL http://localhost:8121/iacs/<section>
    The value of <section> can be any iac that the user enters.
    """
    PrintLogger().info("Now in the show_iac_data function. Section is: " +
                       section)
    my_iac_stub = Iac_Stub()
    data = Iac_Stub.get_iac_stub(
        my_iac_stub, section)  # get the fixed response as a dictionary object
    PrintLogger().info("Data returned successfully")
    data_as_json = json.dumps(
        data,
        separators=(',',
                    ':'))  # convert the dictionary object to a json object
    return Response(data_as_json, mimetype='application/json')
Exemple #5
0
 def __init__(self, output=None, service=None, hostname=None):
     output = output or open('/var/log/metrics.log', "a")
     self.service = service or os.environ.get('SERVICE_NAME')
     self.hostname = hostname or os.environ.get('HOSTNAME')
     self._log = wrap_logger(PrintLogger(output),
                             processors=[add_metadata,
                                         JSONRenderer()])
Exemple #6
0
    def __init__(self, output=None, service=None, namespace=None):

        if USE_STDLIB:
            log = structlog.getLogger(
                processors=[
                    structlog.stdlib.filter_by_level,
                    structlog.stdlib.add_logger_name,
                    structlog.stdlib.add_log_level,
                    structlog.stdlib.PositionalArgumentsFormatter(),
                    structlog.processors.StackInfoRenderer(),
                    structlog.processors.format_exc_info,
                    structlog.processors.UnicodeDecoder(),
                    structlog.stdlib.render_to_log_kwargs,
                ],
                context_class=dict,
                wrapper_class=structlog.stdlib.BoundLogger,
            )
        else:
            log = wrap_logger(PrintLogger(output),
                              processors=[
                                  order_fields,
                                  JSONRenderer(),
                              ])

        if service is None:
            self._service = os.getenv('SERVICE_NAME', '')
        else:
            self._service = service

        self._logger = log.bind(service=self._service)

        if namespace is not None:
            self._logger = self._logger.bind(namespace=namespace)
Exemple #7
0
 def get_reponse_for_eq_stub(self):
     """Create the fixed response, to forward to EQ, as a Python dictionary object. This can then be converted to a json object later on."""
     fixed_response_for_eq =  {'client_ip': None,
                               'event': 'Redirecting to eQ',
                               'level': 'info',
                               'service': 'respondent-home',
                               'created_at': '2018-11-27T12:331543322028'}
     PrintLogger().info("Now returning the fixed response for EQ: " + repr(fixed_response_for_eq))
     return fixed_response_for_eq
 def log(log_type, msg):
     """
     Method to write a log message
     :param log_type: ENUM
     :param msg: String, the message to log
     :return: Nothing
     """
     filename = None
     if log_type == LOG.SPIDER:
         filename = Properties.SPIDER_LOG_FILE
     elif log_type == LOG.CRAWLER:
         filename = Properties.CRAWLER_LOG_FILE
     with open(filename, "a+") as file:
         logger = wrap_logger(logger=PrintLogger(file=file))
         logger.msg(msg)
Exemple #9
0
    def __init__(self, output=None, source=None, namespace=None, service=None):
        log = wrap_logger(PrintLogger(output),
                          processors=[
                              add_timestamp,
                              order_fields,
                              JSONRenderer(),
                              render_wrapp_log,
                          ])

        if not namespace:
            try:
                frame = inspect.currentframe(1)
                namespace = frame.f_globals['__name__']
            except:
                namespace = 'unknown'

        service = service or os.environ.get('SERVICE_NAME')
        self._log = log.bind(namespace=namespace, service=service)
Exemple #10
0
 def get_case_stub(self):
     """Create the fixed case response as a Python dictionary object. This can then be converted to a json object later on."""
     case_fixed_response = {'state':'ACTIONABLE',
                            'id':'0337c579-ce9d-4357-a620-5e4c565cfac1',
                            'actionPlanId':'2cf85a97-8945-453b-a6e8-17668b44f93d',
                            'collectionInstrumentId':'d7f20945-97d4-48c3-9037-532de6dca8fc',
                            'partyId':None,
                            'sampleUnitId':'16cd8fad-b048-46ac-952c-52afc30b47de',
                            'iac':None,
                            'caseRef':'1000000000000002',
                            'createdBy':'SYSTEM',
                            'sampleUnitType':'H',
                            'createdDateTime':'2018-11-01T14:32:00.202Z',
                            'caseGroup': {'collectionExerciseId':'8f604e2c-2e80-421d-8222-8702105ce668',
                                          'id':'cb1f82d1-bc01-4f32-a290-1527df7d8cfc',
                                          'partyId':None,
                                          'sampleUnitRef':'OHS000002',
                                          'sampleUnitType':'H',
                                          'caseGroupStatus':'INPROGRESS'},
                            'responses':[],
                            'caseEvents':None}
     PrintLogger().info("Now returning the case fixed response: " + repr(case_fixed_response))
     return case_fixed_response
apm = ElasticAPM(app)

from structlog import PrintLogger, wrap_logger
from structlog.processors import JSONRenderer
from elasticapm.handlers.structlog import structlog_processor as apm_structlog_processor


def rename_event_key(logger, method_name, event_dict):
    event_dict["message"] = event_dict.pop("event")
    return event_dict


f = open('supermarket.log', 'w')

wrapped_logger = PrintLogger(file=f)
logger = wrap_logger(
    wrapped_logger,
    processors=[
        apm_structlog_processor, rename_event_key,
        structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S"),
        structlog.stdlib.add_log_level, structlog.processors.format_exc_info,
        JSONRenderer()
    ])
log = logger.new()


@app.route('/')
def hello_world():
    x = 3
    y = 42
Exemple #12
0
from structlog import PrintLogger, wrap_logger
from structlog.processors import JSONRenderer, TimeStamper

# renderers must come last
log = wrap_logger(PrintLogger(), processors=[TimeStamper(), JSONRenderer()])
Exemple #13
0
import os, imp, getpass, sys, traceback, re
from pprint import pprint

from twisted.python.filepath import FilePath
from twisted.internet.task import react
from twisted.internet import reactor
from twisted.internet.endpoints import UNIXClientEndpoint
from twisted.conch.ssh.keys import EncryptedKeyError, Key
from twisted.conch.client.knownhosts import KnownHostsFile
from twisted.python import log as logger

import click

from structlog import PrintLogger
log = PrintLogger()

from plait.app.console import ConsoleApp
from plait.app.terminal import TerminalApp
from plait.runner import PlaitRunner
from plait.task import NoSuchTaskError, task
from plait.errors import *
from plait.utils import parse_task_calls, Bag

def findPlaitfile(path=os.getcwd()):
    files = os.listdir(path)
    parent = os.path.dirname(path)
    if 'plaitfile.py' in files:
        fullpath = os.path.join(path, 'plaitfile.py')
        return os.path.abspath(fullpath)
    elif parent != path: