Python logging.ERROR Examples
The following are 30
code examples of logging.ERROR().
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
logging
, or try the search function
.
Example #1
Source File: cmdline.py From BASS with GNU General Public License v2.0 | 9 votes |
def parse_args(): parser = argparse.ArgumentParser(description = "Bass") parser.add_argument("-v", "--verbose", action = "count", default = 0, help = "Increase verbosity") parser.add_argument("samples", metavar = "sample", nargs = "+", help = "Sample path") args = parser.parse_args() try: loglevel = { 0: logging.ERROR, 1: logging.WARN, 2: logging.INFO }[args.verbose] except KeyError: loglevel = logging.DEBUG logging.basicConfig(level = loglevel) logging.getLogger().setLevel(loglevel) return args
Example #2
Source File: client.py From BASS with GNU General Public License v2.0 | 9 votes |
def parse_args(): parser = argparse.ArgumentParser(description = "Find common ngrams in binary files") parser.add_argument("-v", "--verbose", action = "count", default = 0, help = "Increase verbosity") parser.add_argument("--output", type = str, default = None, help = "Output to file instead of stdout") parser.add_argument("--url", type = str, default = "http://localhost:5000", help = "URL of BASS server") parser.add_argument("samples", metavar = "sample", nargs = "+", help = "Cluster samples") args = parser.parse_args() try: loglevel = { 0: logging.ERROR, 1: logging.WARN, 2: logging.INFO}[args.verbose] except KeyError: loglevel = logging.DEBUG logging.basicConfig(level = loglevel) logging.getLogger().setLevel(loglevel) return args
Example #3
Source File: whitelist.py From BASS with GNU General Public License v2.0 | 8 votes |
def parse_args(): parser = argparse.ArgumentParser(description = "Add samples to BASS whitelist") parser.add_argument("-v", "--verbose", action = "count", default = 0, help = "Increase verbosity") parser.add_argument("--url", type = str, default = "http://localhost:5000", help = "URL of BASS server") parser.add_argument("sample", help = "Whitelist sample") args = parser.parse_args() try: loglevel = { 0: logging.ERROR, 1: logging.WARN, 2: logging.INFO}[args.verbose] except KeyError: loglevel = logging.DEBUG logging.basicConfig(level = loglevel) logging.getLogger().setLevel(loglevel) return args
Example #4
Source File: config.py From circleci-demo-python-flask with MIT License | 7 votes |
def init_app(cls, app): Config.init_app(app) # email errors to the administrators import logging from logging.handlers import SMTPHandler credentials = None secure = None if getattr(cls, 'MAIL_USERNAME', None) is not None: credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD) if getattr(cls, 'MAIL_USE_TLS', None): secure = () mail_handler = SMTPHandler( mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT), fromaddr=cls.CIRCULATE_MAIL_SENDER, toaddrs=[cls.CIRCULATE_ADMIN], subject=cls.CIRCULATE_MAIL_SUBJECT_PREFIX + ' Application Error', credentials=credentials, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler)
Example #5
Source File: web.py From svviz with MIT License | 7 votes |
def index(): if not "last_format" in session: session["last_format"] = "svg" session.permanent = True try: variantDescription = str(dataHub.variant).replace("::", " ").replace("-", "–") return render_template('index.html', samples=list(dataHub.samples.keys()), annotations=dataHub.annotationSets, results_table=dataHub.getCounts(), insertSizeDistributions=[sample.name for sample in dataHub if sample.insertSizePlot], dotplots=dataHub.dotplots, variantDescription=variantDescription) except Exception as e: logging.error("ERROR:{}".format(e)) raise
Example #6
Source File: logger.py From dataflow with Apache License 2.0 | 6 votes |
def format(self, record): date = colored('[%(asctime)s @%(filename)s:%(lineno)d]', 'green') msg = '%(message)s' if record.levelno == logging.WARNING: fmt = date + ' ' + colored('WRN', 'red', attrs=['blink']) + ' ' + msg elif record.levelno == logging.ERROR or record.levelno == logging.CRITICAL: fmt = date + ' ' + colored('ERR', 'red', attrs=['blink', 'underline']) + ' ' + msg elif record.levelno == logging.DEBUG: fmt = date + ' ' + colored('DBG', 'yellow', attrs=['blink']) + ' ' + msg else: fmt = date + ' ' + msg if hasattr(self, '_style'): # Python3 compatibility self._style._fmt = fmt self._fmt = fmt return super(_MyFormatter, self).format(record)
Example #7
Source File: config.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def dump_value(self, endpoint_id, item_name, fname, fval): field_type = self._get_field_type(endpoint_id, item_name, fname) if field_type == '': return fval try: field_type = field_type.lower() if field_type == 'bool': return str(fval).lower() elif field_type == 'json': return json.dumps(fval) else: return fval except Exception as exc: msg = 'Fail to dump value of "{type_name}" - ' \ 'endpoint={endpoint}, item={item}, field={field}' \ ''.format(type_name=field_type, endpoint=endpoint_id, item=item_name, field=fname) log(msg, msgx=str(exc), level=logging.ERROR, need_tb=True) raise ConfigException(msg)
Example #8
Source File: log_test.py From tornado-zh with MIT License | 6 votes |
def setUp(self): self.formatter = LogFormatter(color=False) # Fake color support. We can't guarantee anything about the $TERM # variable when the tests are run, so just patch in some values # for testing. (testing with color off fails to expose some potential # encoding issues from the control characters) self.formatter._colors = { logging.ERROR: u("\u0001"), } self.formatter._normal = u("\u0002") # construct a Logger directly to bypass getLogger's caching self.logger = logging.Logger('LogFormatterTest') self.logger.propagate = False self.tempdir = tempfile.mkdtemp() self.filename = os.path.join(self.tempdir, 'log.out') self.handler = self.make_handler(self.filename) self.handler.setFormatter(self.formatter) self.logger.addHandler(self.handler)
Example #9
Source File: log_test.py From tornado-zh with MIT License | 6 votes |
def setUp(self): self.formatter = LogFormatter(color=False) # Fake color support. We can't guarantee anything about the $TERM # variable when the tests are run, so just patch in some values # for testing. (testing with color off fails to expose some potential # encoding issues from the control characters) self.formatter._colors = { logging.ERROR: u("\u0001"), } self.formatter._normal = u("\u0002") # construct a Logger directly to bypass getLogger's caching self.logger = logging.Logger('LogFormatterTest') self.logger.propagate = False self.tempdir = tempfile.mkdtemp() self.filename = os.path.join(self.tempdir, 'log.out') self.handler = self.make_handler(self.filename) self.handler.setFormatter(self.formatter) self.logger.addHandler(self.handler)
Example #10
Source File: config.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def _parse_content(self, endpoint_id, content): """Parse content returned from REST :param content: a JSON string returned from REST. """ try: content = json.loads(content)['entry'] ret = {ent['name']: ent['content'] for ent in content} except Exception as exc: msg = 'Fail to parse content from endpoint_id=%s' \ ' - %s' % (endpoint_id, exc) log(msg, level=logging.ERROR, need_tb=True) raise ConfigException(msg) ret = {name: {key: self.load_value(endpoint_id, name, key, val) for key, val in ent.items() if not key.startswith('eai:')} for name, ent in ret.items()} return ret
Example #11
Source File: lambda_handler.py From aws-auto-remediate with GNU General Public License v3.0 | 6 votes |
def lambda_handler(event, context): logger = logging.getLogger() if logger.handlers: for handler in logger.handlers: logger.removeHandler(handler) # change logging levels for boto and others logging.getLogger("boto3").setLevel(logging.ERROR) logging.getLogger("botocore").setLevel(logging.ERROR) logging.getLogger("urllib3").setLevel(logging.ERROR) # set logging format logging.basicConfig( format="[%(levelname)s] %(message)s (%(filename)s, %(funcName)s(), line %(lineno)d)", level=os.environ.get("LOGLEVEL", "WARNING").upper(), ) # instantiate class retry = Retry(logging) # run functions retry.retry_security_events()
Example #12
Source File: config.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def _get_field_type(self, endpoint_id, item_name, fname): field_types = self._endpoints[endpoint_id].get('field_types', {}) if item_name in field_types: fields = field_types[item_name] elif Config.FIELD_PLACEHOLDER in field_types: fields = field_types[Config.FIELD_PLACEHOLDER] else: fields = {} field_type = fields.get(fname, '') if field_type not in ('', 'bool', 'int', 'json'): msg = 'Unsupported type "{type_name}" for value in schema - ' \ 'endpoint={endpoint}, item={item}, field={field}' \ ''.format(type_name=field_type, endpoint=endpoint_id, item=item_name, field=fname) log(msg, level=logging.ERROR, need_tb=True) raise ConfigException(msg) return field_type
Example #13
Source File: loggingwrapper.py From CAMISIM with Apache License 2.0 | 6 votes |
def set_level(self, level): """ Set the minimum level of messages to be logged. Level of Log Messages CRITICAL 50 ERROR 40 WARNING 30 INFO 20 DEBUG 10 NOTSET 0 @param level: minimum level of messages to be logged @type level: int or long @return: None @rtype: None """ assert level in self._levelNames list_of_handlers = self._logger.handlers for handler in list_of_handlers: handler.setLevel(level)
Example #14
Source File: loggingwrapper.py From CAMISIM with Apache License 2.0 | 6 votes |
def set_level(self, level): """ Set the minimum level of messages to be logged. Level of Log Messages CRITICAL 50 ERROR 40 WARNING 30 INFO 20 DEBUG 10 NOTSET 0 @param level: minimum level of messages to be logged @type level: int or long @return: None @rtype: None """ assert level in self._levelNames list_of_handlers = self._logger.handlers for handler in list_of_handlers: handler.setLevel(level)
Example #15
Source File: config.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def _parse_content(self, endpoint_id, content): """Parse content returned from REST :param content: a JSON string returned from REST. """ try: content = json.loads(content)['entry'] ret = {ent['name']: ent['content'] for ent in content} except Exception as exc: msg = 'Fail to parse content from endpoint_id=%s' \ ' - %s' % (endpoint_id, exc) log(msg, level=logging.ERROR, need_tb=True) raise ConfigException(msg) ret = {name: {key: self.load_value(endpoint_id, name, key, val) for key, val in ent.items() if not key.startswith('eai:')} for name, ent in ret.items()} return ret
Example #16
Source File: test_middleware.py From sanic with MIT License | 6 votes |
def test_middleware_response_raise_cancelled_error(app, caplog): app.config.RESPONSE_TIMEOUT = 1 @app.middleware("response") async def process_response(request, response): raise CancelledError("CancelledError at response middleware") @app.get("/") def handler(request): return text("OK") with caplog.at_level(logging.ERROR): reqrequest, response = app.test_client.get("/") assert response.status == 503 assert ( "sanic.root", logging.ERROR, "Exception occurred while handling uri: 'http://127.0.0.1:42101/'", ) not in caplog.record_tuples
Example #17
Source File: test_middleware.py From sanic with MIT License | 6 votes |
def test_middleware_response_raise_exception(app, caplog): @app.middleware("response") async def process_response(request, response): raise Exception("Exception at response middleware") with caplog.at_level(logging.ERROR): reqrequest, response = app.test_client.get("/fail") assert response.status == 404 # 404 errors are not logged assert ( "sanic.root", logging.ERROR, "Exception occurred while handling uri: 'http://127.0.0.1:42101/'", ) not in caplog.record_tuples # Middleware exception ignored but logged assert ( "sanic.error", logging.ERROR, "Exception occurred in one of response middleware handlers", ) in caplog.record_tuples
Example #18
Source File: test_requests.py From sanic with MIT License | 6 votes |
def test_request_parsing_form_failed(app, caplog): @app.route("/", methods=["POST"]) async def handler(request): return text("OK") payload = "test=OK" headers = {"content-type": "multipart/form-data"} request, response = app.test_client.post( "/", data=payload, headers=headers ) with caplog.at_level(logging.ERROR): request.form assert caplog.record_tuples[-1] == ( "sanic.error", logging.ERROR, "Failed when parsing form", )
Example #19
Source File: test_requests.py From sanic with MIT License | 6 votes |
def test_request_parsing_form_failed_asgi(app, caplog): @app.route("/", methods=["POST"]) async def handler(request): return text("OK") payload = "test=OK" headers = {"content-type": "multipart/form-data"} request, response = await app.asgi_client.post( "/", data=payload, headers=headers ) with caplog.at_level(logging.ERROR): request.form assert caplog.record_tuples[-1] == ( "sanic.error", logging.ERROR, "Failed when parsing form", )
Example #20
Source File: test_app.py From sanic with MIT License | 6 votes |
def test_handle_request_with_nested_sanic_exception(app, monkeypatch, caplog): # Not sure how to raise an exception in app.error_handler.response(), use mock here def mock_error_handler_response(*args, **kwargs): raise SanicException("Mock SanicException") monkeypatch.setattr( app.error_handler, "response", mock_error_handler_response ) @app.get("/") def handler(request): raise Exception with caplog.at_level(logging.ERROR): request, response = app.test_client.get("/") port = request.server_port assert port > 0 assert response.status == 500 assert "Mock SanicException" in response.text assert ( "sanic.root", logging.ERROR, f"Exception occurred while handling uri: 'http://127.0.0.1:{port}/'", ) in caplog.record_tuples
Example #21
Source File: handlers.py From jawfish with MIT License | 6 votes |
def __init__(self, appname, dllname=None, logtype="Application"): logging.Handler.__init__(self) try: import win32evtlogutil, win32evtlog self.appname = appname self._welu = win32evtlogutil if not dllname: dllname = os.path.split(self._welu.__file__) dllname = os.path.split(dllname[0]) dllname = os.path.join(dllname[0], r'win32service.pyd') self.dllname = dllname self.logtype = logtype self._welu.AddSourceToRegistry(appname, dllname, logtype) self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE self.typemap = { logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE, logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE, logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE, logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE, logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, } except ImportError: print("The Python Win32 extensions for NT (service, event "\ "logging) appear not to be available.") self._welu = None
Example #22
Source File: config.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def _get_field_type(self, endpoint_id, item_name, fname): field_types = self._endpoints[endpoint_id].get('field_types', {}) if item_name in field_types: fields = field_types[item_name] elif Config.FIELD_PLACEHOLDER in field_types: fields = field_types[Config.FIELD_PLACEHOLDER] else: fields = {} field_type = fields.get(fname, '') if field_type not in ('', 'bool', 'int', 'json'): msg = 'Unsupported type "{type_name}" for value in schema - ' \ 'endpoint={endpoint}, item={item}, field={field}' \ ''.format(type_name=field_type, endpoint=endpoint_id, item=item_name, field=fname) log(msg, level=logging.ERROR, need_tb=True) raise ConfigException(msg) return field_type
Example #23
Source File: runtests.py From tornado-zh with MIT License | 5 votes |
def filter(self, record): if record.levelno >= logging.ERROR: self.error_count += 1 elif record.levelno >= logging.WARNING: self.warning_count += 1 return True
Example #24
Source File: test_logfail.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def test_log_expected(caplog): with caplog.at_level(logging.ERROR): logging.error('foo')
Example #25
Source File: base_modinput.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def set_log_level(self, level): """Set the log level this python process uses. :param level: log level in `string`. Accept "DEBUG", "INFO", "WARNING", "ERROR" and "CRITICAL". """ if isinstance(level, str): level = level.lower() if level in self.LogLevelMapping: level = self.LogLevelMapping[level] else: level = logging.INFO self.logger.setLevel(level)
Example #26
Source File: alert_actions_base.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def log_error(self, msg): self.message(msg, 'failure', level=logging.ERROR)
Example #27
Source File: messagemock.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def _record_message(self, level, text): log_levels = { usertypes.MessageLevel.error: logging.ERROR, usertypes.MessageLevel.info: logging.INFO, usertypes.MessageLevel.warning: logging.WARNING, } log_level = log_levels[level] logging.getLogger('messagemock').log(log_level, text) self.messages.append(Message(level, text))
Example #28
Source File: log.py From custodia with GNU General Public License v3.0 | 5 votes |
def getLogger(name): """Create logger with custom exception() method """ def exception(self, msg, *args, **kwargs): extra = kwargs.setdefault('extra', {}) extra['exc_fullstack'] = self.isEnabledFor(logging.DEBUG) kwargs['exc_info'] = True self.log(logging.ERROR, msg, *args, **kwargs) logger = logging.getLogger(name) logger.exception = six.create_bound_method(exception, logger) return logger
Example #29
Source File: runtests.py From tornado-zh with MIT License | 5 votes |
def filter(self, record): if record.levelno >= logging.ERROR: self.error_count += 1 elif record.levelno >= logging.WARNING: self.warning_count += 1 return True
Example #30
Source File: logger.py From brutemap with GNU General Public License v3.0 | 5 votes |
def colorize(self, msg): """ Mewarnai pesan """ color = self.color_map[self.record.levelno] reset = Style.RESET_ALL levelname = reset + color + self.record.levelname + reset if self.record.levelname == "CRITICAL": color = self.color_map[logging.ERROR] name = Fore.LIGHTBLUE_EX + self.record.name + reset message = self.record.message # XXX: kenapa cara dibawah ini tidak bekerja? # # match = re.findall(r"['\"]+(.*?)['\"]+", message) # if match: # match.reverse() # for m in match: # message = message.replace(m, color + m + reset, 1) match = re.search(r"=> (?P<account>.*?(?:| \: .*?)) \((?P<status>[A-Z]+)\)", message) if match: account = match.group("account") status = match.group("status") if status == "NO": color_status = Fore.LIGHTRED_EX else: color_status = Fore.LIGHTGREEN_EX newmsg = message.replace(account, color_status + account + reset) newmsg = newmsg.replace(status, color_status + status + reset) msg = msg.replace(message, newmsg) asctime = re.findall(r"\[(.+?)\]", msg)[0] msg = msg.replace(asctime, Fore.LIGHTMAGENTA_EX + asctime + reset, 1) msg = msg.replace(self.record.name, name, 1) msg = msg.replace(self.record.levelname, levelname, 1) msg = msg + reset return msg