Python logging.LoggerAdapter() Examples

The following are 30 code examples for showing how to use logging.LoggerAdapter(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module logging , or try the search function .

Example 1
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        super(LoggerAdapterTest, self).setUp()
        old_handler_list = logging._handlerList[:]

        self.recording = RecordingHandler()
        self.logger = logging.root
        self.logger.addHandler(self.recording)
        self.addCleanup(self.logger.removeHandler, self.recording)
        self.addCleanup(self.recording.close)

        def cleanup():
            logging._handlerList[:] = old_handler_list

        self.addCleanup(cleanup)
        self.addCleanup(logging.shutdown)
        self.adapter = logging.LoggerAdapter(logger=self.logger, extra=None) 
Example 2
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(LoggerAdapterTest, self).setUp()
        old_handler_list = logging._handlerList[:]

        self.recording = RecordingHandler()
        self.logger = logging.root
        self.logger.addHandler(self.recording)
        self.addCleanup(self.logger.removeHandler, self.recording)
        self.addCleanup(self.recording.close)

        def cleanup():
            logging._handlerList[:] = old_handler_list

        self.addCleanup(cleanup)
        self.addCleanup(logging.shutdown)
        self.adapter = logging.LoggerAdapter(logger=self.logger, extra=None) 
Example 3
Project: pyrdp   Author: GoSecure   File: ClipboardMITM.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, client: ClipboardLayer, server: ClipboardLayer, log: LoggerAdapter, recorder: Recorder,
                 statCounter: StatCounter):
        """
        :param client: clipboard layer for the client side
        :param server: clipboard layer for the server side
        :param log: logger for this component
        :param recorder: recorder for clipboard data
        """
        self.statCounter = statCounter
        self.client = client
        self.server = server
        self.log = log
        self.recorder = recorder
        self.forwardNextDataResponse = True

        self.client.createObserver(
            onPDUReceived = self.onClientPDUReceived,
        )

        self.server.createObserver(
            onPDUReceived = self.onServerPDUReceived,
        ) 
Example 4
Project: pyrdp   Author: GoSecure   File: LiveEventHandler.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, viewer: QRemoteDesktop, text: QTextEdit, log: LoggerAdapter, fileSystem: FileSystem, layer: PlayerLayer, tabInstance: LiveTab):
        super().__init__(viewer, text)
        self.log = log
        self.fileSystem = fileSystem
        self.layer = layer
        self.drives: Dict[int, Drive] = {}
        self.downloadDirectories: Dict[str, Directory] = {}
        self.downloadFiles: Dict[str, BinaryIO] = {}
        self.downloadDialogs: Dict[str, FileDownloadDialog] = {}
        self.tabInstance = tabInstance

        # Clicking on an item and "downloading" is a job. Only one job at a time.
        # We need to process each job independently to keep the dialog reliable
        self.jobsQueue = set()
        self.directoryDownloadQueue = set()
        self.fileDownloadQueue = set()
        self.currentDownload = None

        self.handlers[PlayerPDUType.DIRECTORY_LISTING_RESPONSE] = self.handleDirectoryListingResponse
        self.handlers[PlayerPDUType.FILE_DOWNLOAD_RESPONSE] = self.handleDownloadResponse
        self.handlers[PlayerPDUType.FILE_DOWNLOAD_COMPLETE] = self.handleDownloadComplete
        self.handlers[PlayerPDUType.CLIENT_DATA] = self.onClientData
        self.handlers[PlayerPDUType.CONNECTION_CLOSE] = self.onConnectionClose 
Example 5
Project: aitom   Author: xulabs   File: queue_server.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        self.todo_queue = queue.PriorityQueue()
        self.done_queues = {}
        self.done_tasks_time = dict()
        self.done_tasks_time_max = (60.0 * 20)
        self.broadcast_todo_queue = {}
        self.start_calc = {}
        self.out_tasks = {}
        self.proj_alive_time = {}
        self.proj_alive_time_max = (60 * 5)
        self.worker_alive_time = {}
        self.worker_alive_time_max = (60 * 30)
        self.pub_logger = logging.getLogger()
        self.pub_logger.setLevel(logging.WARN)
        if False:
            h = logging.handlers.RotatingFileHandler(filename='./server.log', mode='a', maxBytes=1000000, backupCount=10)
        else:
            h = logging.handlers.RotatingFileHandler(filename='./server.log', mode='a')
        f = logging.Formatter('%(asctime)s %(host)-16s %(job_id)-16s %(source_type)-8s %(levelname)-8s %(message)s')
        h.setFormatter(f)
        self.pub_logger.addHandler(h)
        self.logger = logging.LoggerAdapter(logging.getLogger(), {'host': os.environ.get('HOSTNAME', 'unknown'), 'job_id': os.environ.get('PBS_JOBID', 'N/A').split('.')[0], 'source_type': 'queue_server', })
        self.process = psutil.Process(os.getpid())
        _thread.start_new_thread(QueueServer.remove_dead_projects_daemon, (self,)) 
Example 6
Project: AWS-Transit-Gateway-Demo-MultiAccount   Author: MattTunny   File: crhelper.py    License: MIT License 6 votes vote down vote up
def log_config(event, loglevel=None, botolevel=None):
    if 'ResourceProperties' in event.keys():
        if 'loglevel' in event['ResourceProperties'] and not loglevel:
            loglevel = event['ResourceProperties']['loglevel']
        if 'botolevel' in event['ResourceProperties'] and not botolevel:
            loglevel = event['ResourceProperties']['botolevel']
    if not loglevel:
        loglevel = 'WARNING'
    if not botolevel:
        botolevel = 'ERROR'
    # Set log verbosity levels
    loglevel = getattr(logging, loglevel.upper(), 20)
    botolevel = getattr(logging, botolevel.upper(), 40)
    mainlogger = logging.getLogger()
    mainlogger.setLevel(loglevel)
    logging.getLogger('boto3').setLevel(botolevel)
    logging.getLogger('botocore').setLevel(botolevel)
    # Set log message format
    logfmt = '[%(requestid)s][%(asctime)s][%(levelname)s] %(message)s \n'
    mainlogger.handlers[0].setFormatter(logging.Formatter(logfmt))
    return logging.LoggerAdapter(mainlogger, {'requestid': event['RequestId']}) 
Example 7
Project: AWS-Transit-Gateway-Demo-MultiAccount   Author: MattTunny   File: crhelper.py    License: MIT License 6 votes vote down vote up
def log_config(event, loglevel=None, botolevel=None):
    if 'ResourceProperties' in event.keys():
        if 'loglevel' in event['ResourceProperties'] and not loglevel:
            loglevel = event['ResourceProperties']['loglevel']
        if 'botolevel' in event['ResourceProperties'] and not botolevel:
            loglevel = event['ResourceProperties']['botolevel']
    if not loglevel:
        loglevel = 'WARNING'
    if not botolevel:
        botolevel = 'ERROR'
    # Set log verbosity levels
    loglevel = getattr(logging, loglevel.upper(), 20)
    botolevel = getattr(logging, botolevel.upper(), 40)
    mainlogger = logging.getLogger()
    mainlogger.setLevel(loglevel)
    logging.getLogger('boto3').setLevel(botolevel)
    logging.getLogger('botocore').setLevel(botolevel)
    # Set log message format
    logfmt = '[%(requestid)s][%(asctime)s][%(levelname)s] %(message)s \n'
    mainlogger.handlers[0].setFormatter(logging.Formatter(logfmt))
    return logging.LoggerAdapter(mainlogger, {'requestid': event['RequestId']}) 
Example 8
Project: aws-cloudformation-templates   Author: awslabs   File: crhelper.py    License: Apache License 2.0 6 votes vote down vote up
def log_config(event, loglevel=None, botolevel=None):
    if 'ResourceProperties' in event.keys():
        if 'loglevel' in event['ResourceProperties'] and not loglevel:
            loglevel = event['ResourceProperties']['loglevel']
        if 'botolevel' in event['ResourceProperties'] and not botolevel:
            loglevel = event['ResourceProperties']['botolevel']
    if not loglevel:
        loglevel = 'WARNING'
    if not botolevel:
        botolevel = 'ERROR'
    # Set log verbosity levels
    loglevel = getattr(logging, loglevel.upper(), 20)
    botolevel = getattr(logging, botolevel.upper(), 40)
    mainlogger = logging.getLogger()
    mainlogger.setLevel(loglevel)
    logging.getLogger('boto3').setLevel(botolevel)
    logging.getLogger('botocore').setLevel(botolevel)
    # Set log message format
    logfmt = '[%(requestid)s][%(asctime)s][%(levelname)s] %(message)s \n'
    mainlogger.handlers[0].setFormatter(logging.Formatter(logfmt))
    return logging.LoggerAdapter(mainlogger, {'requestid': event['RequestId']}) 
Example 9
Project: aws-cloudformation-templates   Author: awslabs   File: crhelper.py    License: Apache License 2.0 6 votes vote down vote up
def log_config(event, loglevel=None, botolevel=None):
    if 'ResourceProperties' in event.keys():
        if 'loglevel' in event['ResourceProperties'] and not loglevel:
            loglevel = event['ResourceProperties']['loglevel']
        if 'botolevel' in event['ResourceProperties'] and not botolevel:
            loglevel = event['ResourceProperties']['botolevel']
    if not loglevel:
        loglevel = 'warning'
    if not botolevel:
        botolevel = 'error'
    # Set log verbosity levels
    loglevel = getattr(logging, loglevel.upper(), 20)
    botolevel = getattr(logging, botolevel.upper(), 40)
    mainlogger = logging.getLogger()
    mainlogger.setLevel(loglevel)
    logging.getLogger('boto3').setLevel(botolevel)
    logging.getLogger('botocore').setLevel(botolevel)
    # Set log message format
    logfmt = '[%(requestid)s][%(asctime)s][%(levelname)s] %(message)s \n'
    mainlogger.handlers[0].setFormatter(logging.Formatter(logfmt))
    return logging.LoggerAdapter(mainlogger, {'requestid': event['RequestId']}) 
Example 10
Project: aws-cloudformation-templates   Author: awslabs   File: crhelper.py    License: Apache License 2.0 6 votes vote down vote up
def log_config(event, loglevel=None, botolevel=None):
    if 'ResourceProperties' in event.keys():
        if 'loglevel' in event['ResourceProperties'] and not loglevel:
            loglevel = event['ResourceProperties']['loglevel']
        if 'botolevel' in event['ResourceProperties'] and not botolevel:
            loglevel = event['ResourceProperties']['botolevel']
    if not loglevel:
        loglevel = 'WARNING'
    if not botolevel:
        botolevel = 'ERROR'
    # Set log verbosity levels
    loglevel = getattr(logging, loglevel.upper(), 20)
    botolevel = getattr(logging, botolevel.upper(), 40)
    mainlogger = logging.getLogger()
    mainlogger.setLevel(loglevel)
    logging.getLogger('boto3').setLevel(botolevel)
    logging.getLogger('botocore').setLevel(botolevel)
    # Set log message format
    logfmt = '[%(requestid)s][%(asctime)s][%(levelname)s] %(message)s \n'
    mainlogger.handlers[0].setFormatter(logging.Formatter(logfmt))
    return logging.LoggerAdapter(mainlogger, {'requestid': event['RequestId']}) 
Example 11
def setUp(self):
        super(LoggerAdapterTest, self).setUp()
        old_handler_list = logging._handlerList[:]

        self.recording = RecordingHandler()
        self.logger = logging.root
        self.logger.addHandler(self.recording)
        self.addCleanup(self.logger.removeHandler, self.recording)
        self.addCleanup(self.recording.close)

        def cleanup():
            logging._handlerList[:] = old_handler_list

        self.addCleanup(cleanup)
        self.addCleanup(logging.shutdown)
        self.adapter = logging.LoggerAdapter(logger=self.logger, extra=None) 
Example 12
Project: ambianic-edge   Author: ambianic   File: timeline.py    License: Apache License 2.0 6 votes vote down vote up
def get_event_log(pipeline_context: PipelineContext = None) \
  -> logging.Logger:
    """Get an instance of pipeline event logger.

    :Parameters:
    ----------
    pipe_context : PipelineContext

    :Returns:
    -------
    type
        Implementation of logging.Logger that handles pipeline events

    """
    pipeline_event_log = logging.getLogger(TIMELINE_EVENT_LOGGER_NAME)
    # wrap logger in an adapter that carries pipeline context
    # such as pipeline name and current pipe element.
    pipeline_event_log = logging.LoggerAdapter(
        pipeline_event_log,
        {PIPELINE_CONTEXT_KEY: pipeline_context})
    return pipeline_event_log 
Example 13
Project: kopf   Author: zalando-incubator   File: callbacks.py    License: MIT License 6 votes vote down vote up
def __call__(  # lgtm[py/similar-function]
            self,
            *args: Any,
            type: str,
            event: bodies.RawEvent,
            body: bodies.Body,
            meta: bodies.Meta,
            spec: bodies.Spec,
            status: bodies.Status,
            uid: str,
            name: str,
            namespace: Optional[str],
            patch: patches.Patch,
            logger: Union[logging.Logger, logging.LoggerAdapter],
            **kwargs: Any,
    ) -> _SyncOrAsyncResult: ... 
Example 14
Project: kopf   Author: zalando-incubator   File: callbacks.py    License: MIT License 6 votes vote down vote up
def __call__(  # lgtm[py/similar-function]
            self,
            *args: Any,
            event: str,  # DEPRECATED
            body: bodies.Body,
            meta: bodies.Meta,
            spec: bodies.Spec,
            status: bodies.Status,
            uid: str,
            name: str,
            namespace: Optional[str],
            patch: patches.Patch,
            logger: Union[logging.Logger, logging.LoggerAdapter],
            diff: diffs.Diff,
            old: Optional[Union[bodies.BodyEssence, Any]],  # "Any" is for field-handlers.
            new: Optional[Union[bodies.BodyEssence, Any]],  # "Any" is for field-handlers.
            **kwargs: Any,
    ) -> _SyncOrAsyncResult: ... 
Example 15
Project: kopf   Author: zalando-incubator   File: callbacks.py    License: MIT License 6 votes vote down vote up
def __call__(  # lgtm[py/similar-function]
            self,
            *args: Any,
            type: str,
            event: Union[str, bodies.RawEvent],
            body: bodies.Body,
            meta: bodies.Meta,
            spec: bodies.Spec,
            status: bodies.Status,
            uid: str,
            name: str,
            namespace: Optional[str],
            patch: patches.Patch,
            logger: Union[logging.Logger, logging.LoggerAdapter],
            diff: diffs.Diff,
            old: Optional[Union[bodies.BodyEssence, Any]],  # "Any" is for field-handlers.
            new: Optional[Union[bodies.BodyEssence, Any]],  # "Any" is for field-handlers.
            **kwargs: Any,
    ) -> bool: ... 
Example 16
Project: integrations-core   Author: DataDog   File: query.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run(self, logger=None, **kwargs):
        # type: (Union[logging.Logger, logging.LoggerAdapter], **Any) -> Iterator[Metric]
        if logger is None:
            logger = null_logger  # For convenience in unit tests and example scripts.

        logger.debug('document_query %s', self.name)

        for document, tags in self.source(**kwargs):
            logger.debug('%s %r', self.name, document)

            for spec in self.metrics:
                yield self._make_metric_from_spec(document, spec, tags=tags)

            for enumeration in self.enumerations:
                for metric in self._make_metrics_from_enumeration(document, enumeration, tags=tags):
                    yield metric

            for group in self.groups:
                for metric in self._make_metrics_from_group(document, group, tags=tags):
                    yield metric 
Example 17
Project: king-phisher   Author: rsmusllp   File: signals.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_safe_iter(signal, logger, sender, **kwargs):
	utilities.assert_arg_type(signal, str, 1)
	utilities.assert_arg_type(logger, (logging.Logger, logging.LoggerAdapter), 2)

	signal = blinker.signal(signal)
	for receiver in signal.receivers_for(sender):
		try:
			result = receiver(sender, **kwargs)
		except Exception:
			calling_frame = inspect.stack()[1]
			logger.error("an error occurred while emitting signal '{0}' from {1}:{2}".format(signal, calling_frame[1], calling_frame[2]), exc_info=True)
		else:
			yield (receiver, result)
	return 
Example 18
Project: atomic-reactor   Author: containerbuildsystem   File: exit_koji_import.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def upload_scratch_metadata(self, koji_metadata, koji_upload_dir, koji_session):
        metadata_file = NamedTemporaryFile(prefix="metadata", suffix=".json", mode='wb')
        metadata_file.write(json.dumps(koji_metadata, indent=2).encode('utf-8'))
        metadata_file.flush()

        filename = "metadata.json"
        meta_output = Output(file=metadata_file, metadata={'filename': filename})

        try:
            self.upload_file(koji_session, meta_output, koji_upload_dir)
            path = os.path.join(koji_upload_dir, filename)
            log = logging.LoggerAdapter(self.log, {'arch': METADATA_TAG})
            log.info(path)
        finally:
            meta_output.file.close() 
Example 19
Project: atomic-reactor   Author: containerbuildsystem   File: build_orchestrate_build.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, build, cluster_info, logger):
        self.build = build
        self.cluster = cluster_info.cluster
        self.osbs = cluster_info.osbs
        self.platform = cluster_info.platform
        self.log = logging.LoggerAdapter(logger, {'arch': self.platform})

        self.monitor_exception = None 
Example 20
Project: efs-backup   Author: awslabs   File: logger.py    License: Apache License 2.0 5 votes vote down vote up
def config(self, loglevel='warning'):
        loglevel = logging.getLevelName(loglevel.upper())
        mainlogger = logging.getLogger()
        mainlogger.setLevel(loglevel)

        logfmt = '{"time_stamp": "%(asctime)s", "log_level": "%(levelname)s", "log_message": %(message)s}\n'
        if len(mainlogger.handlers) == 0:
            mainlogger.addHandler(logging.StreamHandler())
        mainlogger.handlers[0].setFormatter(logging.Formatter(logfmt))
        self.log = logging.LoggerAdapter(mainlogger, {}) 
Example 21
Project: DHV3   Author: DuckHunt-discord   File: context.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def logger(self):
        # Copy that to log
        extra = {"channelid" : self.channel.id, "userid": self.author.id}
        logger = logging.LoggerAdapter(self.bot.base_logger, extra)
        return logger 
Example 22
Project: DHV3   Author: DuckHunt-discord   File: ducks.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def logger(self):
        if not self._logger:
            extra = {"channelid": self.channel.id, "userid": 0}
            self._logger = logging.LoggerAdapter(self.bot.base_logger, extra)

        return self._logger 
Example 23
Project: vlcp   Author: hubo1016   File: logger.py    License: Apache License 2.0 5 votes vote down vote up
def process(self, msg, kwargs):
        if 'context' in self.extra:
            m, ka = logging.LoggerAdapter.process(self, msg, kwargs)
            return ('(%s) %s' % (self.extra['context'], m), ka)
        else:
            return logging.LoggerAdapter.process(self, msg, kwargs) 
Example 24
Project: testplan   Author: Morgan-Stanley   File: log.py    License: Apache License 2.0 5 votes vote down vote up
def create_logging_adapter(report):
    """
    Create a new adapter and bind the report to global `REPORT_MAP` so handler
    can access it.
    """

    obj_id = id(report)

    if REPORT_MAP.get(obj_id) is None:
        REPORT_MAP[obj_id] = report

    return logging.LoggerAdapter(LOGGER, {"report_obj_id": obj_id}) 
Example 25
Project: bayesian-coresets   Author: trevorcampbell   File: coreset.py    License: MIT License 5 votes vote down vote up
def __init__(self, initial_wts_sz=1000):
    self.alg_name = self.__class__.__name__ + '-'+secrets.token_hex(3)
    self.log = logging.LoggerAdapter(logging.getLogger(), {"id" : self.alg_name})
    self.reached_numeric_limit = False
    self.nwts = 0
    #internal reps of wts and idcs
    self._wts = np.zeros(initial_wts_sz)
    self._idcs = np.zeros(initial_wts_sz, dtype=np.int64)
    #outward facing views
    self.wts = self._wts[:self.nwts]
    self.idcs = self._idcs[:self.nwts] 
Example 26
Project: bayesian-coresets   Author: trevorcampbell   File: snnls.py    License: MIT License 5 votes vote down vote up
def __init__(self, A, b, check_error_monotone = True):
    self.alg_name = self.__class__.__name__ + '-'+secrets.token_hex(3)
    self.log = logging.LoggerAdapter(logging.getLogger(), {"id" : self.alg_name})
    self.A = A
    self.b = b
    self.reached_numeric_limit = False
    self.w = np.zeros(A.shape[1])
    self.check_error_monotone = check_error_monotone 
Example 27
Project: LLDBagility   Author: quarkslab   File: lldbagilityutils.py    License: Apache License 2.0 5 votes vote down vote up
def create_indented_logger(name, filename):
    filehandler = logging.FileHandler(filename, mode="w")
    filehandler.setFormatter(
        logging.Formatter("%(asctime)s %(name)s %(levelname)s %(prefix)s%(message)s")
    )
    logger = logging.getLogger(name)
    logger.propagate = False
    logger.addHandler(filehandler)
    logger.setLevel(os.getenv("LOGLEVEL", default="WARNING").upper())
    return logging.LoggerAdapter(logger, {"prefix": ""})


# https://stackoverflow.com/questions/26853675/nested-prefixes-accross-loggers-in-python 
Example 28
Project: kale   Author: kubeflow-kale   File: log.py    License: Apache License 2.0 5 votes vote down vote up
def create_adapter(logger, trans_id=None, nb_path=None):
    """Create log Adapter."""
    extras = {"trans_id": trans_id or "",
              "nb_path": os.path.realpath(nb_path) if nb_path else ""}
    return logging.LoggerAdapter(logger, extras) 
Example 29
Project: open-raadsinformatie   Author: openstate   File: log.py    License: MIT License 5 votes vote down vote up
def get_source_logger(name=None):
    logger = logging.getLogger('ocd_backend')

    if name:
        logger = logging.LoggerAdapter(logger, {'source': name})

    return logger 
Example 30
Project: learn_python3_spider   Author: wistbean   File: __init__.py    License: MIT License 5 votes vote down vote up
def logger(self):
        logger = logging.getLogger(self.name)
        return logging.LoggerAdapter(logger, {'spider': self})