Python structlog.get_logger() Examples

The following are 30 code examples of structlog.get_logger(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module structlog , or try the search function .
Example #1
Source File: uni_port.py    From voltha with Apache License 2.0 6 votes vote down vote up
def __init__(self, handler, name, uni_id, port_no, ofp_port_no,
                 type=UniType.PPTP):
        self.log = structlog.get_logger(device_id=handler.device_id,
                                        port_no=port_no)
        self._enabled = False
        self._handler = handler
        self._name = name
        self._port = None
        self._port_number = port_no
        self._ofp_port_no = ofp_port_no
        self._logical_port_number = None
        self._entity_id = None
        self._mac_bridge_port_num = 0
        self._type = type
        self._uni_id = uni_id

        self._admin_state = AdminState.ENABLED
        self._oper_status = OperStatus.ACTIVE 
Example #2
Source File: ldap_groups.py    From build-relengapi with Mozilla Public License 2.0 6 votes vote down vote up
def __init__(self, app):

        permissions_cfg = app.config.get('RELENGAPI_PERMISSIONS', {})
        self.group_permissions = permissions_cfg.get('group-permissions', {})

        # verify that each specified permission exists
        for perm in set(itertools.chain(*self.group_permissions.values())):
            try:
                p[perm]
            except KeyError:
                raise RuntimeError(
                    "invalid permission in settings: %r" % (perm,))

        self.uri = permissions_cfg['uri']
        self.login_dn = permissions_cfg['login_dn']
        self.login_password = permissions_cfg['login_password']
        self.user_base = permissions_cfg['user_base']
        self.group_base = permissions_cfg['group_base']
        self.debug = permissions_cfg.get('debug')

        self.logger = structlog.get_logger()

        permissions_stale.connect_via(app)(self.on_permissions_stale) 
Example #3
Source File: onu_traffic_descriptor.py    From voltha with Apache License 2.0 6 votes vote down vote up
def create(traffic_disc):
        log = structlog.get_logger()
        log.debug('function-entry',traffic_disc=traffic_disc)

        additional = OnuTrafficDescriptor.from_value(
            traffic_disc['additional-bw-eligibility-indicator'])

        # TODO: this is all stub code.  Doesnt do anything yet. tech profiles will likely make this clearer
        best_effort = None

        return OnuTrafficDescriptor(traffic_disc['fixed-bandwidth'],
                                    traffic_disc['assured-bandwidth'],
                                    traffic_disc['maximum-bandwidth'],
                                    name=traffic_disc['name'],
                                    best_effort=best_effort,
                                    additional=additional) 
Example #4
Source File: log.py    From fleece with Apache License 2.0 6 votes vote down vote up
def get_logger(
    name=None,
    level=None,
    stream=DEFAULT_STREAM,
    clobber_root_handler=True,
    logger_factory=None,
    wrapper_class=None,
):
    """Configure and return a logger with structlog and stdlib."""
    _configure_logger(logger_factory=logger_factory, wrapper_class=wrapper_class)
    log = structlog.get_logger(name)
    root_logger = logging.root
    if log == root_logger:
        if not _has_streamhandler(root_logger, level=level, stream=stream):
            stream_handler = logging.StreamHandler(stream)
            stream_handler.setLevel(level)
            stream_handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT))
            root_logger.addHandler(stream_handler)
        else:
            if clobber_root_handler:
                for handler in root_logger.handlers:
                    handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT))
    if level:
        log.setLevel(level)
    return log 
Example #5
Source File: brcm_mib_sync.py    From voltha with Apache License 2.0 6 votes vote down vote up
def __init__(self, agent, device_id, mib_sync_tasks, db,
                 advertise_events=False):
        """
        Class initialization

        :param agent: (OpenOmciAgent) Agent
        :param device_id: (str) ONU Device ID
        :param db: (MibDbVolatileDict) MIB Database
        :param mib_sync_tasks: (dict) Tasks to run
        :param advertise_events: (bool) Advertise events on OpenOMCI Event Bus
        """
        self.log = structlog.get_logger(device_id=device_id)
        self.log.debug('function-entry')

        super(BrcmMibSynchronizer, self).__init__(agent, device_id, mib_sync_tasks, db,
                                                  advertise_events=advertise_events) 
Example #6
Source File: log.py    From synse-server with GNU General Public License v3.0 6 votes vote down vote up
def override_sanic_loggers():
    # Override Sanic loggers with structlog loggers. Unfortunately
    # there isn't a great way of doing this because the Sanic modules
    # already hold a reference to the logging.Logger at import load,
    # so we are stuck with just replacing those references in their
    # respective modules.
    root = structlog.get_logger('sanic.root')
    error = structlog.get_logger('sanic.error')

    app.error_logger = error
    app.logger = root
    asgi.logger = root
    handlers.logger = root
    request.logger = root
    request.error_logger = error
    server.logger = root 
Example #7
Source File: onu_configuration.py    From voltha with Apache License 2.0 6 votes vote down vote up
def __init__(self, omci_agent, device_id):
        """
        Initialize this instance of the OnuConfiguration class

        :param omci_agent: (OpenOMCIAgent) agent reference
        :param device_id: (str) ONU Device ID

        :raises KeyError: If ONU Device is not registered with OpenOMCI
        """
        self.log = structlog.get_logger(device_id=device_id)
        self._device_id = device_id
        self._onu_device = omci_agent.get_device(device_id)

        # The capabilities
        self._attributes = None
        self.reset() 
Example #8
Source File: broadcom_onu.py    From voltha with Apache License 2.0 6 votes vote down vote up
def __init__(self, adapter, device_id):
        self.adapter = adapter
        self.adapter_agent = adapter.adapter_agent
        self.device_id = device_id
        self.log = structlog.get_logger(device_id=device_id)
        self.incoming_messages = DeferredQueue()
        self.event_messages = DeferredQueue()
        self.proxy_address = None
        self.tx_id = 0
        self.flow_map = dict()

        # Need to query ONU for number of supported uni ports
        # For now, temporarily set number of ports to 1 - port #2
        self.uni_ports = (1, 2, 3, 4, 5)
        self.flow_config_in_progress = False

        # Handle received ONU event messages
        reactor.callLater(0, self.handle_onu_events) 
Example #9
Source File: __main__.py    From k8s-snapshots with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def shutdown(*, loop=None):
    _logger = structlog.get_logger()
    global _shutdown
    if _shutdown:
        _logger.warning('Already shutting down')
        return

    _shutdown = True

    _logger.debug(
        'shutting down',
    )

    print_tasks()

    _logger.info('Shutdown complete') 
Example #10
Source File: pon_port.py    From voltha with Apache License 2.0 6 votes vote down vote up
def __init__(self, handler, port_no):
        self.log = structlog.get_logger(device_id=handler.device_id, port_no=port_no)
        self.log.debug('function-entry')

        self._enabled = False
        self._valid = True
        self._handler = handler
        self._deferred = None
        self._port = None
        self._port_number = port_no
        self._next_entity_id = PonPort.MIN_GEM_ENTITY_ID

        self._admin_state = AdminState.ENABLED
        self._oper_status = OperStatus.ACTIVE

        self._gem_ports = {}                           # gem-id -> GemPort
        self._tconts = {}                              # alloc-id -> TCont

        self.ieee_mapper_service_profile_entity_id = 0x8001
        self.mac_bridge_port_ani_entity_id = 0x2102  # TODO: can we just use the entity id from the anis list? 
Example #11
Source File: uni_port.py    From voltha with Apache License 2.0 6 votes vote down vote up
def __init__(self, handler, name, port_no, ofp_port_no):
        self.log = structlog.get_logger(device_id=handler.device_id, port_no=port_no)
        self._enabled = False
        self._handler = handler
        self._name = name
        self.uni_id = platform.uni_id_from_uni_port(port_no)
        self._port = None
        self._port_number = port_no
        self._ofp_port_no = ofp_port_no         # Set at by creator (vENET create)
        self._logical_port_number = None        # Set at time of logical port creation
        self._entity_id = None                  # TODO: Use port number from UNI-G entity ID
        self._mac_bridge_port_num = 0

        self._admin_state = AdminState.ENABLED
        self._oper_status = OperStatus.ACTIVE
        # TODO Add state, stats, alarm reference, ...
        pass 
Example #12
Source File: pon_port.py    From voltha with Apache License 2.0 6 votes vote down vote up
def __init__(self, handler, port_no):
        self.log = structlog.get_logger(device_id=handler.device_id, port_no=port_no)

        self._enabled = False
        self._valid = True
        self._handler = handler
        self._deferred = None
        self._port = None
        self._port_number = port_no
        self._entity_id = None                  # ANI entity ID
        self._next_entity_id = PonPort.MIN_GEM_ENTITY_ID

        self._admin_state = AdminState.ENABLED
        self._oper_status = OperStatus.ACTIVE

        self._gem_ports = {}                           # gem-id -> GemPort
        self._tconts = {}                              # alloc-id -> TCont

        # OMCI resources
        # TODO: These could be dynamically chosen (can be most any value)
        self.ieee_mapper_service_profile_entity_id = 0x100
        self.mac_bridge_port_ani_entity_id = 0x100 
Example #13
Source File: ponsim_olt.py    From voltha with Apache License 2.0 6 votes vote down vote up
def __init__(self, adapter, device_id):
        self.adapter = adapter
        self.adapter_agent = adapter.adapter_agent
        self.device_id = device_id
        self.log = structlog.get_logger(device_id=device_id)
        self.channel = None
        self.io_port = None
        self.logical_device_id = None
        self.nni_port = None
        self.ofp_port_no = None
        self.interface = registry('main').get_args().interface
        self.ponsim_comm = registry('main').get_args().ponsim_comm
        self.pm_metrics = None
        self.alarms = None
        self.frames = None
        self.ctag_map = {} 
Example #14
Source File: tlgs_onu.py    From voltha with Apache License 2.0 6 votes vote down vote up
def __init__(self, adapter, device_id):
        self.adapter = adapter
        self.adapter_agent = adapter.adapter_agent
        self.device_id = device_id
        self.log = structlog.get_logger(device_id=device_id)
        #self.incoming_messages = Queue.Queue()
        self.incoming_messages = DeferredQueue()
        self.event_messages = Queue.Queue()
        self.proxy_address = None
        self.tx_id = 0
        self.trangen = sequence_generator(1)
        self.port_id = None
        self.alloc_id = None
        self.cvlan_id = None
        self.subsvlan_id = None
        self.bandwidth = None
        self.flows_lock = 0
        self.flows = None
        self.policy_id = None
        self.flow_queue = DeferredQueue() 
Example #15
Source File: grpc_client.py    From voltha with Apache License 2.0 6 votes vote down vote up
def __init__(self, connection_manager, channel, grpc_timeout):

        self.log = get_logger()

        self.connection_manager = connection_manager
        self.channel = channel
        self.grpc_timeout = grpc_timeout
        self.local_stub = VolthaLocalServiceStub(channel)

        self.stopped = False

        self.packet_out_queue = Queue()  # queue to send out PacketOut msgs
        self.packet_in_queue = DeferredQueue()  # queue to receive PacketIn
        self.change_event_queue = DeferredQueue()  # queue change events

        self.count_pkt_in = 0
        self.count_pkt_out = 0 
Example #16
Source File: exchange.py    From crypto-signal with MIT License 6 votes vote down vote up
def __init__(self, exchange_config):
        """Initializes ExchangeInterface class

        Args:
            exchange_config (dict): A dictionary containing configuration for the exchanges.
        """

        self.logger = structlog.get_logger()
        self.exchanges = dict()

        # Loads the exchanges using ccxt.
        for exchange in exchange_config:
            if exchange_config[exchange]['required']['enabled']:
                new_exchange = getattr(ccxt, exchange)({
                    "enableRateLimit": True
                })

                # sets up api permissions for user if given
                if new_exchange:
                    self.exchanges[new_exchange.id] = new_exchange
                else:
                    self.logger.error("Unable to load exchange %s", new_exchange) 
Example #17
Source File: app.py    From crypto-signal with MIT License 6 votes vote down vote up
def main():
    """Initializes the application
    """
     # Load settings and create the config object
    config = Configuration()
    settings = config.settings

    # Set up logger
    logs.configure_logging(settings['log_level'], settings['log_mode'])
    logger = structlog.get_logger()

    # Configure and run configured behaviour.
    exchange_interface = ExchangeInterface(config.exchanges)
    notifier = Notifier(config.notifiers)

    behaviour = Behaviour(
        config,
        exchange_interface,
        notifier
    )

    while True:
        behaviour.run(settings['market_pairs'], settings['output_mode'])
        logger.info("Sleeping for %s seconds", settings['update_interval'])
        time.sleep(settings['update_interval']) 
Example #18
Source File: behaviour.py    From crypto-signal with MIT License 6 votes vote down vote up
def __init__(self, config, exchange_interface, notifier):
        """Initializes DefaultBehaviour class.

        Args:
            indicator_conf (dict): A dictionary of configuration for this analyzer.
            exchange_interface (ExchangeInterface): Instance of the ExchangeInterface class for
                making exchange queries.
            notifier (Notifier): Instance of the notifier class for informing a user when a
                threshold has been crossed.
        """

        self.logger = structlog.get_logger()
        self.indicator_conf = config.indicators
        self.informant_conf = config.informants
        self.crossover_conf = config.crossovers
        self.exchange_interface = exchange_interface
        self.strategy_analyzer = StrategyAnalyzer()
        self.notifier = notifier

        output_interface = Output()
        self.output = output_interface.dispatcher 
Example #19
Source File: app.py    From GovLens with MIT License 6 votes vote down vote up
def __config_logger__(self):
        logging.basicConfig(
            level=logging.INFO, format=self.log_format, stream=sys.stdout,
        )

        structlog.configure(
            processors=[
                structlog.stdlib.filter_by_level,
                structlog.stdlib.PositionalArgumentsFormatter(),
                structlog.processors.StackInfoRenderer(),
                structlog.processors.format_exc_info,
                structlog.processors.JSONRenderer(),
            ],
            logger_factory=structlog.stdlib.LoggerFactory(),
            wrapper_class=structlog.stdlib.BoundLogger,
        )
        return structlog.get_logger("Startup") 
Example #20
Source File: ponsim.py    From voltha with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.log = structlog.get_logger() 
Example #21
Source File: device_agent.py    From voltha with Apache License 2.0 5 votes vote down vote up
def __init__(self, core, initial_data):

        self.core = core
        self._tmp_initial_data = initial_data
        self.last_data = None
        self.calback_data = None

        self.proxy = core.get_proxy('/devices/{}'.format(initial_data.id))
        self.flows_proxy = core.get_proxy(
            '/devices/{}/flows'.format(initial_data.id))
        self.groups_proxy = core.get_proxy(
            '/devices/{}/flow_groups'.format(initial_data.id))

        self.pm_config_proxy = core.get_proxy(
            '/devices/{}/pm_configs'.format(initial_data.id))

        self.img_dnld_proxies = {}

        self.proxy.register_callback(
            CallbackType.PRE_UPDATE, self._validate_update)
        self.proxy.register_callback(
            CallbackType.POST_UPDATE, self._process_update)

        self.flows_proxy.register_callback(
            CallbackType.PRE_UPDATE, self._pre_process_flows)

        self.flows_proxy.register_callback(
            CallbackType.POST_UPDATE, self._flow_table_updated)
        self.groups_proxy.register_callback(
            CallbackType.POST_UPDATE, self._group_table_updated)

        self.pm_config_proxy.register_callback(
            CallbackType.POST_UPDATE, self._pm_config_updated)

        # to know device capabilities
        self.device_type = core.get_proxy(
            '/device_types/{}'.format(initial_data.type)).get()

        self.adapter_agent = None
        self.flow_changes = None
        self.log = structlog.get_logger(device_id=initial_data.id) 
Example #22
Source File: ponsim.py    From voltha with Apache License 2.0 5 votes vote down vote up
def __init__(self, name, logical_port_no):
        self.name = name
        self.logical_port_no = logical_port_no
        self.links = dict()
        self.flows = list()
        self.log = structlog.get_logger(name=name,
                                        logical_port_no=logical_port_no)
        self.counter = FrameIOCounter(name) 
Example #23
Source File: onu_tcont.py    From voltha with Apache License 2.0 5 votes vote down vote up
def create(handler, tcont, td):
        log = structlog.get_logger(tcont=tcont, td=td)
        log.debug('function-entry', tcont=tcont)

        return OnuTCont(handler,
                        tcont['uni_id'],
                        tcont['alloc-id'],
                        tcont['q_sched_policy'],
                        td
                        ) 
Example #24
Source File: ponsim_onu.py    From voltha with Apache License 2.0 5 votes vote down vote up
def __init__(self, adapter, device_id):
        self.adapter = adapter
        self.adapter_agent = adapter.adapter_agent
        self.device_id = device_id
        self.log = structlog.get_logger(device_id=device_id)
        self.incoming_messages = DeferredQueue()
        self.proxy_address = None
        # reference of uni_port is required when re-enabling the device if
        # it was disabled previously
        self.uni_port = None
        self.pon_port = None 
Example #25
Source File: onu_tcont.py    From voltha with Apache License 2.0 5 votes vote down vote up
def __init__(self, handler, uni_id, alloc_id, q_sched_policy, traffic_descriptor):

        self.log = structlog.get_logger(device_id=handler.device_id, uni_id=uni_id, alloc_id=alloc_id)
        self.log.debug('function-entry')

        self.uni_id = uni_id
        self.alloc_id = alloc_id
        self._q_sched_policy = 0
        self.q_sched_policy = q_sched_policy
        self.traffic_descriptor = traffic_descriptor

        self._handler = handler
        self._entity_id = None 
Example #26
Source File: onu_traffic_descriptor.py    From voltha with Apache License 2.0 5 votes vote down vote up
def from_value(value):
        log = structlog.get_logger()
        log.debug('function-entry', value=value)
        return {
            0: NONE,
            1: BEST_EFFORT_SHARING,
            2: NON_ASSURED_SHARING,
        }.get(value, DEFAULT) 
Example #27
Source File: onu_traffic_descriptor.py    From voltha with Apache License 2.0 5 votes vote down vote up
def to_string(value):
        log = structlog.get_logger()
        log.debug('function-entry', value=value)
        return {
            NON_ASSURED_SHARING: "non-assured-sharing",
            BEST_EFFORT_SHARING: "best-effort-sharing",
            NONE: "none"
        }.get(value, "unknown") 
Example #28
Source File: pon_port.py    From voltha with Apache License 2.0 5 votes vote down vote up
def create(handler, port_no):
        log = structlog.get_logger(device_id=handler.device_id, port_no=port_no)
        log.debug('function-entry')
        port = PonPort(handler, port_no)

        return port 
Example #29
Source File: openolt_device.py    From voltha with Apache License 2.0 5 votes vote down vote up
def __init__(self, **kwargs):
        super(OpenoltDevice, self).__init__()

        self.admin_state = "up"

        adapter_agent = kwargs['adapter_agent']
        self.device_id = kwargs['device_id']

        self.data_model_class = kwargs['support_classes']['data_model']
        self.platform_class = kwargs['support_classes']['platform']
        self.platform = self.platform_class()
        self.resource_mgr_class = kwargs['support_classes']['resource_mgr']
        self.flow_mgr_class = kwargs['support_classes']['flow_mgr']
        self.alarm_mgr_class = kwargs['support_classes']['alarm_mgr']
        self.stats_mgr_class = kwargs['support_classes']['stats_mgr']

        is_reconciliation = kwargs.get('reconciliation', False)
        self.host_and_port = kwargs['host_and_port']
        self.extra_args = kwargs['extra_args']
        self.log = structlog.get_logger(ip=self.host_and_port)

        self.log.info('openolt-device-init')

        self.data_model = self.data_model_class(self.device_id, adapter_agent,
                                                self.platform)
        if is_reconciliation:
            self.log.info('reconcile data model')
            self.data_model.reconcile()

        # Initialize the OLT state machine
        self.machine = Machine(model=self, states=OpenoltDevice.states,
                               transitions=OpenoltDevice.transitions,
                               send_event=True, initial='state_null')

        self.device_info = None

        self.go_state_init() 
Example #30
Source File: logging.py    From chainerui with MIT License 5 votes vote down vote up
def get_logger():
    global _logger

    with _mutex:
        if _logger is not None:
            return _logger
        structlog.configure(
            processors=[
                structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
            ],
            logger_factory=structlog.stdlib.LoggerFactory(),
        )

        own_logger = _get_library_logger()
        if not logging.getLogger().handlers:
            # own hander is set only when python root logger is not setup
            formatter = structlog.stdlib.ProcessorFormatter(
                processor=structlog.dev.ConsoleRenderer(colors=False),
            )
            handler = logging.StreamHandler()
            handler.setFormatter(formatter)
            own_logger.addHandler(handler)

        own_logger.setLevel(logging.INFO)
        _logger = structlog.get_logger(__name__)
    return _logger