Python logging.log() Examples

The following are 30 code examples for showing how to use logging.log(). 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: 3vilTwinAttacker   Author: wi-fi-analyzer   File: ServerConnection.py    License: MIT License 6 votes vote down vote up
def handleHeader(self, key, value):
        logging.log(self.getLogLevel(), "Got server header: %s:%s" % (key, value))

        if (key.lower() == 'location'):
            value = self.replaceSecureLinks(value)

        if (key.lower() == 'content-type'):
            if (value.find('image') != -1):
                self.isImageRequest = True
                logging.debug("Response is image content, not scanning...")

        if (key.lower() == 'content-encoding'):
            if (value.find('gzip') != -1):
                logging.debug("Response is compressed...")
                self.isCompressed = True
        elif (key.lower() == 'content-length'):
            self.contentLength = value
        elif (key.lower() == 'set-cookie'):
            self.client.responseHeaders.addRawHeader(key, value)
        elif (key.lower()== 'strict-transport-security'):
        	logging.log(self.getLogLevel(), "LEO Erasing Strict Transport Security....")
        else:
            self.client.setHeader(key, value) 
Example 2
Project: Facedancer   Author: usb-tools   File: greatdancer.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send_on_endpoint(self, ep_num, data, blocking=True):
        """
        Sends a collection of USB data on a given endpoint.

        ep_num: The number of the IN endpoint on which data should be sent.
        data: The data to be sent.
        blocking: If true, this function will wait for the transfer to complete.
        """
        logging.log(LOGLEVEL_TRACE, f"EP{ep_num}/IN: <- {bytes(data)}")

        self._wait_until_ready_to_send(ep_num)
        self.api.send_on_endpoint(ep_num, bytes(data))

        # If we're blocking, wait until the transfer completes.
        if blocking:
            while not self._transfer_is_complete(ep_num, self.DEVICE_TO_HOST):
                pass

        self._clean_up_transfers_for_endpoint(ep_num, self.DEVICE_TO_HOST) 
Example 3
Project: instaclone   Author: vivlabs   File: log_calls.py    License: Apache License 2.0 6 votes vote down vote up
def log_calls_with(severity):
  """Create a decorator to log calls and return values of any function, for debugging."""

  def decorator(fn):
    @functools.wraps(fn)
    def wrap(*params, **kwargs):
      call_str = "%s(%s)" % (
        fn.__name__, ", ".join([repr(p) for p in params] + ["%s=%s" % (k, repr(v)) for (k, v) in kwargs.items()]))
      # TODO: Extract line number from caller and use that in logging.
      log(severity, ">> %s", call_str)
      ret = fn(*params, **kwargs)
      # TODO: Add a way to make return short or omitted.
      log(severity, "<< %s: %s", call_str, repr(ret))
      return ret

    return wrap

  return decorator

# Convenience decorators for logging. 
Example 4
Project: TabPy   Author: tableau   File: state.py    License: MIT License 6 votes vote down vote up
def _set_config_value(
        self,
        section_name,
        option_name,
        option_value,
        logger=logging.getLogger(__name__),
        _update_revision=True,
    ):
        if not self.config:
            raise ValueError("State configuration not yet loaded.")

        if not self.config.has_section(section_name):
            logger.log(logging.DEBUG, f"Adding config section {section_name}")
            self.config.add_section(section_name)

        self.config.set(section_name, option_name, option_value)
        # update revision number
        if _update_revision:
            self._increase_revision_number()
        self._write_state(logger=logger) 
Example 5
Project: dket   Author: dkmfbk   File: runtime.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _step(self):
        step, _, loss, summary, targets, predictions, lengths = self._sess.run(self._fetches)

        logging.log(HDEBUG, 'computing donwstream metrics')
        metrics = dict((key, metric.reset().compute(targets, predictions, lengths))
                       for (key, metric) in self._metrics.items())

        save_step = self._ckpt_every == 0 or (step % self._ckpt_every == 0)
        ckpt = self._save_ckpt(step) if save_step else None
        self._summarize(step, loss, summary, metrics, ckpt=ckpt)
        if ckpt and self._eval:
            self._eval.start(ckpt)

        next_step = self._steps == 0 or step < self._steps
        logging.log(HDEBUG, 'next step: %s', str(next_step))
        return step, next_step 
Example 6
Project: jd_analysis   Author: awolfly9   File: utils.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def kill_ports(ports):
    for port in ports:
        log('kill %s start' % port)
        popen = subprocess.Popen('lsof -i:%s' % port, shell = True, stdout = subprocess.PIPE)
        (data, err) = popen.communicate()
        log('data:\n%s  \nerr:\n%s' % (data, err))

        pattern = re.compile(r'\b\d+\b', re.S)
        pids = re.findall(pattern, data)

        log('pids:%s' % str(pids))

        for pid in pids:
            if pid != '' and pid != None:
                try:
                    log('pid:%s' % pid)
                    popen = subprocess.Popen('kill -9 %s' % pid, shell = True, stdout = subprocess.PIPE)
                    (data, err) = popen.communicate()
                    log('data:\n%s  \nerr:\n%s' % (data, err))
                except Exception, e:
                    log('kill_ports exception:%s' % e)

        log('kill %s finish' % port) 
Example 7
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: dec.py    License: Apache License 2.0 5 votes vote down vote up
def setup(self, X, num_centers, alpha, save_to='dec_model'):
        sep = X.shape[0]*9//10
        X_train = X[:sep]
        X_val = X[sep:]
        ae_model = AutoEncoderModel(self.xpu, [X.shape[1],500,500,2000,10], pt_dropout=0.2)
        if not os.path.exists(save_to+'_pt.arg'):
            ae_model.layerwise_pretrain(X_train, 256, 50000, 'sgd', l_rate=0.1, decay=0.0,
                                        lr_scheduler=mx.misc.FactorScheduler(20000,0.1))
            ae_model.finetune(X_train, 256, 100000, 'sgd', l_rate=0.1, decay=0.0,
                              lr_scheduler=mx.misc.FactorScheduler(20000,0.1))
            ae_model.save(save_to+'_pt.arg')
            logging.log(logging.INFO, "Autoencoder Training error: %f"%ae_model.eval(X_train))
            logging.log(logging.INFO, "Autoencoder Validation error: %f"%ae_model.eval(X_val))
        else:
            ae_model.load(save_to+'_pt.arg')
        self.ae_model = ae_model

        self.dec_op = DECModel.DECLoss(num_centers, alpha)
        label = mx.sym.Variable('label')
        self.feature = self.ae_model.encoder
        self.loss = self.dec_op(data=self.ae_model.encoder, label=label, name='dec')
        self.args.update({k:v for k,v in self.ae_model.args.items() if k in self.ae_model.encoder.list_arguments()})
        self.args['dec_mu'] = mx.nd.empty((num_centers, self.ae_model.dims[-1]), ctx=self.xpu)
        self.args_grad.update({k: mx.nd.empty(v.shape, ctx=self.xpu) for k,v in self.args.items()})
        self.args_mult.update({k: k.endswith('bias') and 2.0 or 1.0 for k in self.args})
        self.num_centers = num_centers 
Example 8
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: dec.py    License: Apache License 2.0 5 votes vote down vote up
def mnist_exp(xpu):
    X, Y = data.get_mnist()
    dec_model = DECModel(xpu, X, 10, 1.0, 'data/mnist')
    acc = []
    for i in [10*(2**j) for j in range(9)]:
        acc.append(dec_model.cluster(X, Y, i))
        logging.log(logging.INFO, 'Clustering Acc: %f at update interval: %d'%(acc[-1], i))
    logging.info(str(acc))
    logging.info('Best Clustering ACC: %f at update_interval: %d'%(np.max(acc), 10*(2**np.argmax(acc)))) 
Example 9
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: solver.py    License: Apache License 2.0 5 votes vote down vote up
def forward_end(self, i, internals):
        if i % self.interval == 0 and logging.getLogger().isEnabledFor(self.level):
            for key in sorted(internals.keys()):
                arr = internals[key]
                logging.log(self.level, 'Iter:%d  param:%s\t\tstat(%s):%s',
                            i, key, self.stat.__name__, str(self.stat(arr.asnumpy()))) 
Example 10
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: solver.py    License: Apache License 2.0 5 votes vote down vote up
def backward_end(self, i, weights, grads, metric=None):
        if i % self.interval == 0 and logging.getLogger().isEnabledFor(self.level):
            for key in sorted(grads.keys()):
                arr = grads[key]
                logging.log(self.level, 'Iter:%d  param:%s\t\tstat(%s):%s\t\tgrad_stat:%s',
                            i, key, self.stat.__name__,
                            str(self.stat(weights[key].asnumpy())), str(self.stat(arr.asnumpy())))
        if i % self.interval == 0 and metric is not None:
            logging.log(logging.INFO, 'Iter:%d metric:%f', i, metric.get()[1])
            metric.reset() 
Example 11
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: solver.py    License: Apache License 2.0 5 votes vote down vote up
def backward_end(self, i, weights, grads, metric=None):
        if i % self.interval == 0 and logging.getLogger().isEnabledFor(self.level):
            for key in sorted(grads.keys()):
                arr = grads[key]
                logging.log(self.level, 'Iter:%d  param:%s\t\tstat(%s):%s\t\tgrad_stat:%s',
                            i, key, self.stat.__name__,
                            str(self.stat(weights[key].asnumpy())), str(self.stat(arr.asnumpy())))
        if i % self.interval == 0 and metric is not None:
            logging.log(logging.INFO, 'Iter:%d metric:%f', i, metric.get()[1])
            metric.reset() 
Example 12
Project: SecPi   Author: SecPi   File: testaction.py    License: GNU General Public License v3.0 5 votes vote down vote up
def execute(self):
		logging.log("Executing Test Action!")
		if 'msg' in self.params:
			logging.log("Test Action Message: %s"%self.params['msg']) 
Example 13
Project: easy-faster-rcnn.pytorch   Author: potterhsu   File: logger.py    License: MIT License 5 votes vote down vote up
def log(level, message):
        assert Logger.Initialized, 'Logger has not been initialized'
        logging.log(level, message) 
Example 14
Project: easy-faster-rcnn.pytorch   Author: potterhsu   File: logger.py    License: MIT License 5 votes vote down vote up
def d(message):
        Logger.log(logging.DEBUG, message) 
Example 15
Project: easy-faster-rcnn.pytorch   Author: potterhsu   File: logger.py    License: MIT License 5 votes vote down vote up
def i(message):
        Logger.log(logging.INFO, message) 
Example 16
Project: easy-faster-rcnn.pytorch   Author: potterhsu   File: logger.py    License: MIT License 5 votes vote down vote up
def w(message):
        Logger.log(logging.WARNING, message) 
Example 17
Project: easy-faster-rcnn.pytorch   Author: potterhsu   File: logger.py    License: MIT License 5 votes vote down vote up
def e(message):
        Logger.log(logging.ERROR, message) 
Example 18
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: ServerConnection.py    License: MIT License 5 votes vote down vote up
def sendRequest(self):
        logging.log(self.getLogLevel(), "Sending Request: %s %s"  % (self.command, self.uri))
        self.sendCommand(self.command, self.uri) 
Example 19
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: ServerConnection.py    License: MIT License 5 votes vote down vote up
def sendHeaders(self):
        for header, value in self.headers.items():
            logging.log(self.getLogLevel(), "Sending header: %s : %s" % (header, value))
            self.sendHeader(header, value)

        self.endHeaders() 
Example 20
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: ServerConnection.py    License: MIT License 5 votes vote down vote up
def connectionMade(self):
        logging.log(self.getLogLevel(), "HTTP connection made.")
        self.sendRequest()
        self.sendHeaders()
        
        if (self.command == 'POST'):
            self.sendPostData() 
Example 21
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: ServerConnection.py    License: MIT License 5 votes vote down vote up
def handleStatus(self, version, code, message):
        logging.log(self.getLogLevel(), "Got server response: %s %s %s" % (version, code, message))
        self.client.setResponseCode(int(code), message) 
Example 22
Project: minidump   Author: skelsec   File: SystemInfoStream.py    License: MIT License 5 votes vote down vote up
def parse(dir, buff):
		t = MinidumpSystemInfo()
		buff.seek(dir.Location.Rva)
		chunk = io.BytesIO(buff.read(dir.Location.DataSize))
		si = MINIDUMP_SYSTEM_INFO.parse(chunk)
		t.ProcessorArchitecture = si.ProcessorArchitecture
		t.ProcessorLevel = si.ProcessorLevel
		t.ProcessorRevision = si.ProcessorRevision
		t.NumberOfProcessors = si.NumberOfProcessors
		t.ProductType = si.ProductType
		t.MajorVersion = si.MajorVersion
		t.MinorVersion = si.MinorVersion
		t.BuildNumber = si.BuildNumber
		t.PlatformId = si.PlatformId
		t.CSDVersion = MINIDUMP_STRING.get_from_rva(si.CSDVersionRva, buff)
		t.SuiteMask = si.SuiteMask
		t.VendorId = si.VendorId
		t.VersionInformation = si.VersionInformation
		t.FeatureInformation = si.FeatureInformation
		t.AMDExtendedCpuFeatures = si.AMDExtendedCpuFeatures
		t.ProcessorFeatures = si.ProcessorFeatures
		try:
			t.guess_os()
		except Exception as e:
			logging.log(1, 'Failed to guess OS! MajorVersion: %s MinorVersion %s BuildNumber %s ProductType: %s' % (t.MajorVersion, t.MinorVersion, t.BuildNumber, t.ProductType ))
			t.OperatingSystem = None
		return t 
Example 23
Project: moler   Author: nokia   File: connection.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def identity_transformation(data):
    """Default coder is no encoding/decoding"""
    logging.log(logging.WARNING, "identity_transformation from connection.py is deprecated now. Please use"
                                 " abstract_moler_connection.py.")
    return data 
Example 24
Project: Facedancer   Author: usb-tools   File: greatdancer.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def stall_endpoint(self, ep_num, direction=0):
        """
        Stalls the provided endpoint, as defined in the USB spec.

        ep_num: The number of the endpoint to be stalled.
        """

        in_vs_out = "IN" if direction else "OUT"
        logging.log(LOGLEVEL_TRACE, "Stalling EP{} {}".format(ep_num, in_vs_out))

        self.endpoint_stalled[ep_num] = True
        self.api.stall_endpoint(self._endpoint_address(ep_num, direction)) 
Example 25
Project: Facedancer   Author: usb-tools   File: device.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def handle_generic_get_descriptor_request(self, request: USBControlRequest):
        """ Handle GET_DESCRIPTOR requests; per USB2 [9.4.3] """

        logging.debug(f"received GET_DESCRIPTOR request {request}")

        # Extract the core parameters from the request.
        descriptor_type  = request.value_high
        descriptor_index = request.value_low

        # Try to find the descriptor associate with the request.
        response = self.descriptors.get(descriptor_type, None)

        # If we have a callable, we need to evaluate it to figure
        # out what the actual descriptor should be.
        while callable(response):
            response = response(descriptor_index)

        # If we wound up with a valid response, reply with it.
        if response:
            response_length = min(request.length, len(response))
            request.reply(response[:response_length])

            logging.log(LOGLEVEL_TRACE, f"sending {response_length} bytes in response")
        else:
            logging.log(LOGLEVEL_TRACE, f"stalling descriptor request")
            request.stall() 
Example 26
Project: browserscope   Author: elsigh   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def log(cls, *args, **kwargs):
    return Log(*args, **kwargs) 
Example 27
Project: browserscope   Author: elsigh   File: dev_appserver.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, text, log):
    self.text = text
    self.log = log 
Example 28
Project: browserscope   Author: elsigh   File: dev_appserver.py    License: Apache License 2.0 5 votes vote down vote up
def _GenerateRequestLogId():
  """Generates the request log id for the current request."""
  sec = int(_request_time)
  usec = int(1000000 * (_request_time - sec))
  h = hashlib.sha1(str(_request_id)).digest()[:4]
  packed = struct.Struct('> L L').pack(sec, usec)
  return binascii.b2a_hex(packed + h) 
Example 29
Project: browserscope   Author: elsigh   File: dev_appserver.py    License: Apache License 2.0 5 votes vote down vote up
def log_message(self, format, *args):
      """Redirect log messages through the logging module."""


      if hasattr(self, 'path') and self.channel_poll_path_re.match(self.path):
        logging.debug(format, *args)
      else:
        logging.info(format, *args) 
Example 30
Project: IPProxyTool   Author: awolfly9   File: utils.py    License: MIT License 5 votes vote down vote up
def log(msg, level = logging.DEBUG):
    logging.log(level, msg)
    print('%s [%s], msg:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), level, msg))

    if level == logging.WARNING or level == logging.ERROR:
        for line in traceback.format_stack():
            print(line.strip())

        for line in traceback.format_stack():
            logging.log(level, line.strip())


# 服务器使用,清理端口占用