Python logging.ERROR() Examples

The following are code examples for showing how to use logging.ERROR(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
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 2
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_nested_explicit(self):
        # Logging levels in a nested namespace, all explicitly set.
        m = self.next_message

        INF = logging.getLogger("INF")
        INF.setLevel(logging.INFO)
        INF_ERR  = logging.getLogger("INF.ERR")
        INF_ERR.setLevel(logging.ERROR)

        # These should log.
        INF_ERR.log(logging.CRITICAL, m())
        INF_ERR.error(m())

        # These should not log.
        INF_ERR.warn(m())
        INF_ERR.info(m())
        INF_ERR.debug(m())

        self.assert_log_lines([
            ('INF.ERR', 'CRITICAL', '1'),
            ('INF.ERR', 'ERROR', '2'),
        ]) 
Example 3
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_config_10_ok(self):
        with captured_stdout() as output:
            self.apply_config(self.config10)
            logger = logging.getLogger("compiler.parser")
            logger.warning(self.next_message())
            logger = logging.getLogger('compiler')
            #Not output, because filtered
            logger.warning(self.next_message())
            logger = logging.getLogger('compiler.lexer')
            #Not output, because filtered
            logger.warning(self.next_message())
            logger = logging.getLogger("compiler.parser.codegen")
            #Output, as not filtered
            logger.error(self.next_message())
            self.assert_log_lines([
                ('WARNING', '1'),
                ('ERROR', '4'),
            ], stream=output) 
Example 4
Project: logging-test-case   Author: chadrosenquist   File: loggingtestcase_example.py    MIT License 6 votes vote down vote up
def test_fail(self):
        """
        Run a test that fails.

        Notice that the error message is logged to the console.
        This allows for easier debugging.

        Here is the output:
        ======================================================================
        ERROR: test_fail (examples.example1.Example1)
        ----------------------------------------------------------------------
        Traceback (most recent call last):
          File "D:\Git\logging-test-case\examples\loggingtestcase_example.py.py", line 61,
          in test_fail raise FileNotFoundError("Failed to open file.")
        FileNotFoundError: Failed to open file.

        ERROR:examples.example1:Failed to open file.
        ----------------------------------------------------------------------
        """
        self.logger.error("Failed to open file.")
        raise FileNotFoundError("Failed to open file.") 
Example 5
Project: BASS   Author: Cisco-Talos   File: cmdline.py    GNU General Public License v2.0 6 votes vote down vote up
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 6
Project: BASS   Author: Cisco-Talos   File: whitelist.py    GNU General Public License v2.0 6 votes vote down vote up
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 7
Project: BASS   Author: Cisco-Talos   File: client.py    GNU General Public License v2.0 6 votes vote down vote up
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 8
Project: ieml   Author: IEMLdev   File: lexer.py    GNU General Public License v3.0 6 votes vote down vote up
def get_script_lexer(module=None):
    t_LAYER0_MARK = r'\:'
    t_LAYER1_MARK = r'\.'
    t_LAYER2_MARK = r'\-'
    t_LAYER3_MARK = r'[\'\’]'
    t_LAYER4_MARK = r'\,'
    t_LAYER5_MARK = r'\_'
    t_LAYER6_MARK = r'\;'

    t_PRIMITIVE = r'[EUASBT]'
    t_REMARKABLE_ADDITION = r'[OMFI]'
    t_REMARKABLE_MULTIPLICATION = r'wo|wa|y|o|e|wu|we|u|a|i|j|g|s|b|t|h|c|k|m|n|p|x|d|f|l'
    t_PLUS = r'\+'

    t_ignore = ' \t\n'

    # Error handling rule
    def t_error(t):
        logger.log(logging.ERROR, "Illegal character '%s'" % t.value[0])
        t.lexer.skip(1)

    return lxr.lex(module=module, errorlog=logging) 
Example 9
Project: Autoline   Author: zjh1218   File: config.py    Apache License 2.0 6 votes vote down vote up
def init_app(cls, app):
        Config.init_app(app)

        # 发送初始化错误信息给管理员
        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.FLASKY_MAIL_SENDER,
            toaddrs=[cls.FLASKY_ADMIN],
            subject=cls.FLASKY_MAIL_SUBJECT_PREFIX + ' AutoLine Startup Error',
            credentials=credentials,
            secure=secure)

        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler) 
Example 10
Project: aws-auto-remediate   Author: servian   File: lambda_handler.py    GNU General Public License v3.0 6 votes vote down vote up
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 11
Project: flasky   Author: RoseOu   File: log.py    MIT License 6 votes vote down vote up
def deprecated(self, removal_version, msg, *args, **kwargs):
        """
        Logs deprecation message which is log level WARN if the
        ``removal_version`` is > 1 minor release away and log level ERROR
        otherwise.

        removal_version should be the version that the deprecated feature is
        expected to be removed in, so something that will not exist in
        version 1.7, but will in 1.6 would have a removal_version of 1.7.
        """
        from pip import __version__

        if should_warn(__version__, removal_version):
            self.warn(msg, *args, **kwargs)
        else:
            self.error(msg, *args, **kwargs) 
Example 12
Project: flasky   Author: RoseOu   File: config.py    MIT License 6 votes vote down vote up
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.FLASKY_MAIL_SENDER,
            toaddrs=[cls.FLASKY_ADMIN],
            subject=cls.FLASKY_MAIL_SUBJECT_PREFIX + ' Application Error',
            credentials=credentials,
            secure=secure)
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler) 
Example 13
Project: brb   Author: Prograsaur   File: logutils.py    GNU General Public License v3.0 6 votes vote down vote up
def init_logger(suffix, logpath='log', loglevel=logging.INFO):
    loglevel = loglevel_to_int(loglevel)

    if not os.path.exists(logpath): os.makedirs(logpath)

    recfmt = '(%(threadName)s) %(asctime)s.%(msecs)03d %(levelname)s %(filename)s:%(lineno)d %(message)s'
    timefmt = '%Y-%m-%d %H:%M:%S'

    logging.basicConfig(filename=time.strftime(f'{logpath}/FS-{suffix}.%Y%m%d_%H%M%S.log'),
                        filemode="w",
                        level=loglevel,
                        format=recfmt, datefmt=timefmt)

    logger = logging.getLogger()
    console = logging.StreamHandler()
    console.setLevel(logging.ERROR)
    logger.addHandler(console)

    return logger
#endregion Utils

#region main
#------------------------------------------------------------------------------- 
Example 14
Project: vulnerability-engine   Author: RedHatInsights   File: test_upload_listener.py    GNU General Public License v2.0 6 votes vote down vote up
def test_delete_system(self, pg_db_conn, caplog):  # pylint: disable=unused-argument
        """Test deleting a system."""
        with DatabasePool(1):
            # make sure system is in DB
            db_import_system(A_SYSTEM, A_SYSTEM['vmaas-json'], [])

            # now delete the system
            rtrn = db_delete_system(A_SYSTEM)
            assert rtrn['deleted']
            assert not rtrn['failed']

            # try to delete it again
            rtrn = db_delete_system(A_SYSTEM)
            assert not rtrn['deleted']
            assert not rtrn['failed']

            # try to delete system with invalid id
            with caplog.at_level(logging.ERROR):
                rtrn = db_delete_system({'id': 0})
            assert not rtrn['deleted']
            assert rtrn['failed']
            assert caplog.records[0].msg.startswith("Error deleting system:")
            caplog.clear() 
Example 15
Project: AshsSDK   Author: thehappydinoa   File: clidriver.py    MIT License 6 votes vote down vote up
def _handle_top_level_args(self, args):
        emit_top_level_args_parsed_event(self.session, args)
        if args.profile:
            self.session.set_config_variable('profile', args.profile)
        if args.debug:
            # TODO:
            # Unfortunately, by setting debug mode here, we miss out
            # on all of the debug events prior to this such as the
            # loading of plugins, etc.
            self.session.set_stream_logger('botocore', logging.DEBUG,
                                           format_string=LOG_FORMAT)
            self.session.set_stream_logger('awscli', logging.DEBUG,
                                           format_string=LOG_FORMAT)
            self.session.set_stream_logger('s3transfer', logging.DEBUG,
                                           format_string=LOG_FORMAT)
            LOG.debug("CLI version: %s", self.session.user_agent())
            LOG.debug("Arguments entered to CLI: %s", sys.argv[1:])

        else:
            self.session.set_stream_logger(logger_name='awscli',
                                           log_level=logging.ERROR) 
Example 16
Project: SpaceXLaunchBot   Author: r-spacex   File: utils.py    MIT License 6 votes vote down vote up
def setup_logging() -> None:
    """Setup logging.

    These settings will apply to any logging.info, error, debug, etc. call from now on
    This uses logging.basicConfig to setup the logging usage, which means this function
    has to be called before anything else even imports logging, otherwise the
    configuration set by this will not be used.
    """
    log_file_handler = logging.handlers.TimedRotatingFileHandler(
        filename=config.LOG_PATH, when="W0", backupCount=10, encoding="UTF-8"
    )
    log_file_handler.setFormatter(logging.Formatter(config.LOG_FORMAT))

    logging.basicConfig(level=config.LOG_LEVEL, handlers=[log_file_handler])

    # Change discord to only log ERROR level and above
    logging.getLogger("discord").setLevel(logging.ERROR) 
Example 17
Project: csvpandas   Author: crosenth   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def setup_logging(namespace):
    """
    setup global logging
    """

    loglevel = {
        0: logging.ERROR,
        1: logging.WARNING,
        2: logging.INFO,
        3: logging.DEBUG,
    }.get(namespace.verbosity, logging.DEBUG)

    if namespace.verbosity > 1:
        logformat = '%(levelname)s csvpandas %(lineno)s %(message)s'
    else:
        logformat = 'csvpandas %(message)s'

    logging.basicConfig(stream=namespace.log, format=logformat, level=loglevel) 
Example 18
Project: web-scraper   Author: keeper-of-data   File: log.py    MIT License 6 votes vote down vote up
def setup_custom_logger(name, log_file):

    # Create logger
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    # Create file handler which logs error messages
    fh = logging.FileHandler(log_file)
    fh.setLevel(logging.ERROR)
    # Create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.CRITICAL)
    # Create formatter and add it to the handlers
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(module)s - %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    # Add the handlers to the logger
    logger.addHandler(fh)
    logger.addHandler(ch)

    return logger 
Example 19
Project: openhatch   Author: campbe13   File: test_log.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def test_logging_proxy(self):
        logger = self.setup_logger(loglevel=logging.ERROR, logfile=None,
                                   root=False)

        with wrap_logger(logger) as sio:
            p = LoggingProxy(logger, loglevel=logging.ERROR)
            p.close()
            p.write("foo")
            self.assertNotIn("foo", sio.getvalue())
            p.closed = False
            p.write("foo")
            self.assertIn("foo", sio.getvalue())
            lines = ["baz", "xuzzy"]
            p.writelines(lines)
            for line in lines:
                self.assertIn(line, sio.getvalue())
            p.flush()
            p.close()
            self.assertFalse(p.isatty())
            self.assertIsNone(p.fileno()) 
Example 20
Project: fs_image   Author: facebookincubator   File: btrfs_loopback.py    MIT License 5 votes vote down vote up
def _minimize_image_size(
    *, unshare: Optional[Unshare], cur_size: int, image_path: bytes,
    mount_path: bytes, loop_dev: bytes,
) -> int:
    'Returns the new filesystem size.'
    min_size_out = subprocess.check_output(nsenter_as_root(
        unshare, 'btrfs', 'inspect-internal', 'min-dev-size', mount_path,
    )).split(b' ')
    assert min_size_out[1] == b'bytes'
    min_size = _fix_up_fs_size(int(min_size_out[0]), MIN_SHRINK_BYTES)
    if min_size >= cur_size:
        log.info(
            f'Nothing to do: the minimum resize limit {min_size} is no less '
            f'than the current filesystem size of {cur_size} bytes.'
        )
        return
    log.info(f'Shrinking {image_path} to the btrfs minimum, {min_size} bytes')
    run_stdout_to_err(nsenter_as_root(
        unshare, 'btrfs', 'filesystem', 'resize', str(min_size),
        mount_path,
    ), check=True)
    fs_bytes = int(subprocess.check_output(nsenter_as_user(
        unshare, 'findmnt', '--bytes', '--noheadings', '--output', 'SIZE',
        mount_path,
    )))
    # Log an error on size rounding since this is not expected to need it.
    _create_or_resize_image_file(image_path, fs_bytes, log_level=logging.ERROR)
    run_stdout_to_err([
        'sudo', 'losetup', '--set-capacity', loop_dev,
    ], check=True)
    return min_size 
Example 21
Project: leapp-repository   Author: oamg   File: ntp2chrony.py    Apache License 2.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description="Convert ntp configuration to chrony.")
    parser.add_argument("-r", "--root", dest="roots", default=["/"], nargs="+",
                        metavar="DIR", help="specify root directory (default /)")
    parser.add_argument("--ntp-conf", action="store", default="/etc/ntp.conf",
                        metavar="FILE", help="specify ntp config (default /etc/ntp.conf)")
    parser.add_argument("--step-tickers", action="store", default="",
                        metavar="FILE", help="specify ntpdate step-tickers config (no default)")
    parser.add_argument("--chrony-conf", action="store", default="/etc/chrony.conf",
                        metavar="FILE", help="specify chrony config (default /etc/chrony.conf)")
    parser.add_argument("--chrony-keys", action="store", default="/etc/chrony.keys",
                        metavar="FILE", help="specify chrony keyfile (default /etc/chrony.keys)")
    parser.add_argument("-b", "--backup", action="store_true", help="backup existing configs before writing")
    parser.add_argument("-L", "--ignored-lines", action="store_true", help="print ignored lines")
    parser.add_argument("-D", "--ignored-directives", action="store_true",
                        help="print names of ignored directives")
    parser.add_argument("-n", "--dry-run", action="store_true", help="don't make any changes")
    parser.add_argument("-v", "--verbose", action="count", default=0, help="increase verbosity")

    args = parser.parse_args()

    logging.basicConfig(format="%(message)s",
                        level=[logging.ERROR, logging.INFO, logging.DEBUG][min(args.verbose, 2)])

    for root in args.roots:
        conf = NtpConfiguration(root, args.ntp_conf, args.step_tickers)

        if args.ignored_lines:
            for line in conf.ignored_lines:
                print(line)

        if args.ignored_directives:
            for directive in conf.ignored_directives:
                print(directive)

        conf.write_chrony_configuration(args.chrony_conf, args.chrony_keys, args.dry_run, args.backup) 
Example 22
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getEventType(self, record):
        """
        Return the event type for the record.

        Override this if you want to specify your own types. This version does
        a mapping using the handler's typemap attribute, which is set up in
        __init__() to a dictionary which contains mappings for DEBUG, INFO,
        WARNING, ERROR and CRITICAL. If you are using your own levels you will
        either need to override this method or place a suitable dictionary in
        the handler's typemap attribute.
        """
        return self.typemap.get(record.levelno, self.deftype) 
Example 23
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, capacity, flushLevel=logging.ERROR, target=None):
        """
        Initialize the handler with the buffer size, the level at which
        flushing should occur and an optional target.

        Note that without a target being set either here or via setTarget(),
        a MemoryHandler is no use to anyone!
        """
        BufferingHandler.__init__(self, capacity)
        self.flushLevel = flushLevel
        self.target = target 
Example 24
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_config0_ok(self):
        # A simple config file which overrides the default settings.
        with captured_stdout() as output:
            self.apply_config(self.config0)
            logger = logging.getLogger()
            # Won't output anything
            logger.info(self.next_message())
            # Outputs a message
            logger.error(self.next_message())
            self.assert_log_lines([
                ('ERROR', '2'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([]) 
Example 25
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_config1_ok(self, config=config1):
        # A config file defining a sub-parser as well.
        with captured_stdout() as output:
            self.apply_config(config)
            logger = logging.getLogger("compiler.parser")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            self.assert_log_lines([
                ('INFO', '1'),
                ('ERROR', '2'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([]) 
Example 26
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_config4_ok(self):
        # A config file specifying a custom formatter class.
        with captured_stdout() as output:
            self.apply_config(self.config4)
            logger = logging.getLogger()
            try:
                raise RuntimeError()
            except RuntimeError:
                logging.exception("just testing")
            sys.stdout.seek(0)
            self.assertEqual(output.getvalue(),
                "ERROR:root:just testing\nGot a [RuntimeError]\n")
            # Original logger output is empty
            self.assert_log_lines([]) 
Example 27
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_config0_ok(self):
        # A simple config which overrides the default settings.
        with captured_stdout() as output:
            self.apply_config(self.config0)
            logger = logging.getLogger()
            # Won't output anything
            logger.info(self.next_message())
            # Outputs a message
            logger.error(self.next_message())
            self.assert_log_lines([
                ('ERROR', '2'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([]) 
Example 28
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_config4_ok(self):
        # A config specifying a custom formatter class.
        with captured_stdout() as output:
            self.apply_config(self.config4)
            #logger = logging.getLogger()
            try:
                raise RuntimeError()
            except RuntimeError:
                logging.exception("just testing")
            sys.stdout.seek(0)
            self.assertEqual(output.getvalue(),
                "ERROR:root:just testing\nGot a [RuntimeError]\n")
            # Original logger output is empty
            self.assert_log_lines([]) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_config4a_ok(self):
        # A config specifying a custom formatter class.
        with captured_stdout() as output:
            self.apply_config(self.config4a)
            #logger = logging.getLogger()
            try:
                raise RuntimeError()
            except RuntimeError:
                logging.exception("just testing")
            sys.stdout.seek(0)
            self.assertEqual(output.getvalue(),
                "ERROR:root:just testing\nGot a [RuntimeError]\n")
            # Original logger output is empty
            self.assert_log_lines([]) 
Example 30
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_config7_ok(self):
        with captured_stdout() as output:
            self.apply_config(self.config1)
            logger = logging.getLogger("compiler.parser")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            self.assert_log_lines([
                ('INFO', '1'),
                ('ERROR', '2'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([])
        with captured_stdout() as output:
            self.apply_config(self.config7)
            logger = logging.getLogger("compiler.parser")
            self.assertTrue(logger.disabled)
            logger = logging.getLogger("compiler.lexer")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            self.assert_log_lines([
                ('INFO', '3'),
                ('ERROR', '4'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([])

    #Same as test_config_7_ok but don't disable old loggers. 
Example 31
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_config_8_ok(self):
        with captured_stdout() as output:
            self.apply_config(self.config1)
            logger = logging.getLogger("compiler.parser")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            self.assert_log_lines([
                ('INFO', '1'),
                ('ERROR', '2'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([])
        with captured_stdout() as output:
            self.apply_config(self.config8)
            logger = logging.getLogger("compiler.parser")
            self.assertFalse(logger.disabled)
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            logger = logging.getLogger("compiler.lexer")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            self.assert_log_lines([
                ('INFO', '3'),
                ('ERROR', '4'),
                ('INFO', '5'),
                ('ERROR', '6'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([]) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_listen_config_1_ok(self):
        with captured_stdout() as output:
            self.setup_via_listener(textwrap.dedent(ConfigFileTest.config1))
            logger = logging.getLogger("compiler.parser")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            self.assert_log_lines([
                ('INFO', '1'),
                ('ERROR', '2'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([]) 
Example 33
Project: drydock   Author: airshipit   File: base.py    Apache License 2.0 5 votes vote down vote up
def error(self, ctx, msg):
        self.log_error(ctx, logging.ERROR, msg) 
Example 34
Project: drydock   Author: airshipit   File: base.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.log_level = 'ERROR'
        self.user = None  # Username
        self.user_id = None  # User ID (UUID)
        self.user_domain_id = None  # Domain owning user
        self.roles = []
        self.project_id = None
        self.project_domain_id = None  # Domain owning project
        self.is_admin_project = False
        self.authenticated = False
        self.request_id = str(uuid.uuid4())
        self.external_marker = ''
        self.policy_engine = None
        self.end_user = None  # Initial User 
Example 35
Project: logging-test-case   Author: chadrosenquist   File: assertnologs_example1.py    MIT License 5 votes vote down vote up
def __init__(self, methodName='runTest', testlogger=None, testlevel=None):
        """
        To change the logger or log level, override __init__.
        By default, the root logger is used and the log level is logging.INFO.
        """
        # testlevel = logging.ERROR
        super().__init__(methodName, testlogger, testlevel) 
Example 36
Project: logging-test-case   Author: chadrosenquist   File: assertnologs_example1.py    MIT License 5 votes vote down vote up
def test_assert_no_logs_fail(self):
        """The test fails because logs are emitted.

        Here is the output:
        E               AssertionError: The follow messages were unexpectedly logged:
        E                   ERROR:examples.assertnologs_example1:first message
        E                   ERROR:examples.assertnologs_example1:second message

        """
        with self.assertNoLogs():
            self.logger.error('first message')
            self.logger.error('second message') 
Example 37
Project: logging-test-case   Author: chadrosenquist   File: loggingtestcase_example.py    MIT License 5 votes vote down vote up
def __init__(self, methodName='runTest', testlogger=None, testlevel=None):
        """
        To change the logger or log level, override __init__.
        By default, the root logger is used and the log level is logging.INFO.
        """
        # testlevel = logging.ERROR
        super().__init__(methodName, testlogger, testlevel) 
Example 38
Project: logging-test-case   Author: chadrosenquist   File: simpleloggingtests.py    MIT License 5 votes vote down vote up
def __init__(self, methodName='runTest', testlogger=None, testlevel=None):
        testlevel = logging.ERROR
        super().__init__(methodName, testlogger, testlevel) 
Example 39
Project: Flask-pyoidc   Author: zamzterz   File: test_flask_pyoidc.py    Apache License 2.0 5 votes vote down vote up
def test_logout_handles_redirect_back_from_provider_with_incorrect_state(self, caplog):
        authn = self.init_app()
        logout_view_mock = self.get_view_mock()
        state = 'some_state'
        with self.app.test_request_context('/logout?state={}'.format(state)):
            flask.session['end_session_state'] = 'other_state'
            result = authn.oidc_logout(logout_view_mock)()
            assert 'end_session_state' not in flask.session

        self.assert_view_mock(logout_view_mock, result)
        assert caplog.record_tuples[-1] == ('flask_pyoidc.flask_pyoidc',
                                            logging.ERROR,
                                            "Got unexpected state '{}' after logout redirect.".format(state)) 
Example 40
Project: ieml   Author: IEMLdev   File: lexer.py    GNU General Public License v3.0 5 votes vote down vote up
def get_lexer(module=None):
    t_OLD_MORPHEME_GRAMMATICAL_CLASS = r'E:\.b\.E:[SBT]:\.-'

    t_MORPHEME = TERM_REGEX
    # t_PLUS   = r'\+'
    # t_TIMES   = r'\*'
    t_LPAREN  = r'\('
    t_RPAREN  = r'\)'
    # t_LCHEVRON = r'\<'
    t_RCHEVRON = r'\>'

    t_LBRACKET = r'\['
    t_RBRACKET  = r'\]'
    t_EXCLAMATION_MARK  = r'\!'
    #

    t_LITERAL = r'\#(\\\#|[^\#])+\#'

    t_GROUP_MULTIPLICITY = r'm\d+'

    t_ignore  = '{} \t\n'

    # Error handling rule
    def t_error(t):
        logger.log(logging.ERROR, "Illegal character '%s'" % t.value[0])
        t.lexer.skip(1)

    return lxr.lex(module=module, errorlog=logging) 
Example 41
Project: ieml   Author: IEMLdev   File: lexer.py    GNU General Public License v3.0 5 votes vote down vote up
def get_lexer(module=None):
    t_COORD_KIND = r'[%s]'%''.join(COORDINATES_KINDS)
    t_COORD_INDEX = r'\d+'
    t_PLUS   = r'\+'
    t_LPAREN  = r'\('
    t_RPAREN  = r'\)'
    t_COLON = r':'
    t_ignore  = ' \t\n'

    # Error handling rule
    def t_error(t):
        logger.log(logging.ERROR, "Illegal character '%s'" % t.value[0])
        t.lexer.skip(1)

    return lxr.lex(module=module, errorlog=logging) 
Example 42
Project: chess-chiller   Author: fsmosca   File: chess-chiller.py    GNU General Public License v3.0 5 votes vote down vote up
def initialize_logger(logger_level):
    """ Save logs to file, use RotatingFileHandler to avoid disk space overrun """
    logger = logging.getLogger()
    logger.setLevel(logger_level)
     
    # Creates console handler for info/warning/error/critical logs
    handler = logging.StreamHandler()
    handler.setLevel(logging.INFO)
    formatter = logging.Formatter("%(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
 
    # Creates error/critical file handler
    handler = RotatingFileHandler("error.log", mode='w',
                                  maxBytes=5000000, backupCount=5)  
    handler.setLevel(logging.ERROR)
    formatter = logging.Formatter("%(asctime)s [%(threadName)-10.10s] [%(funcName)-12.12s] [%(levelname)-5.5s] > %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
 
    # Creates debug/info/warning/error/critical file handler
    handler = RotatingFileHandler("all.log", mode='w',
                                  maxBytes=5000000, backupCount=5)   
    handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s [%(threadName)-10.10s] [%(funcName)-12.12s] [%(levelname)-5.5s] > %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler) 
Example 43
Project: aws-auto-remediate   Author: servian   File: lambda_handler.py    GNU General Public License v3.0 5 votes vote down vote up
def lambda_handler(event, context):
    loggger = logging.getLogger()

    if loggger.handlers:
        for handler in loggger.handlers:
            loggger.removeHandler(handler)

    # change logging levels for boto and others to prevent log spamming
    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"),
    )

    # add SNS logger
    # sns_logger = SNSLoggingHandler(os.environ.get('LOGTOPIC'))
    # sns_logger.setLevel(logging.INFO)
    # loggger.addHandler(sns_logger)

    # instantiate class
    remediate = Remediate(logging, event)

    # run functions
    remediate.remediate() 
Example 44
Project: aws-auto-remediate   Author: servian   File: lambda_handler.py    GNU General Public License v3.0 5 votes vote down vote up
def lambda_handler(event, context):
    loggger = logging.getLogger()

    if loggger.handlers:
        for handler in loggger.handlers:
            loggger.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
    setup = Setup(logging)

    # run functions
    setup.setup_dynamodb()

    settings = setup.get_settings()

    setup.create_stacks("config_rules", settings)
    setup.create_stacks("custom_rules", settings) 
Example 45
Project: pnp   Author: HazardDede   File: test_logging_slack.py    MIT License 5 votes vote down vote up
def test_logger_emit_for_smoke(slacker_mock):
    slacker_mock.return_value = MagicMock()

    dut = SlackHandler(
        api_key='doesnt_matter',
        channel='pytest',
        fire_and_forget=False
    )
    dut.emit(LogRecord(
        name='pytest',
        level=logging.ERROR,
        pathname='doesnt_matter',
        lineno=42,
        msg='LogRecord from pytest',
        args=None,
        exc_info=None
    ))

    slacker_mock.return_value.chat.post_message.assert_called_once_with(
        text=None,
        channel='#pytest',
        username=SlackHandler.DEFAULT_USERNAME,
        icon_url=None,
        icon_emoji=SlackHandler.DEFAULT_EMOJI,
        attachments=[{
            'color': 'danger',
            'fields': [{'title': 'LogRecord from pytest', 'short': False}]
        }]
    ) 
Example 46
Project: pnp   Author: HazardDede   File: test_logging_slack.py    MIT License 5 votes vote down vote up
def test_logger_emit_with_trace(slacker_mock):
    slacker_mock.return_value = MagicMock()

    dut = SlackHandler(
        api_key='doesnt_matter',
        channel='pytest',
        fire_and_forget=False
    )
    dut.MAX_ATTACHMENT_CHARS = 46
    try:
        raise Exception("EXCEPTION RAISED ON PURPOSE!")
    except Exception:
        dut.emit(LogRecord(
            name='pytest',
            level=logging.ERROR,
            pathname='doesnt_matter',
            lineno=42,
            msg='LogRecord from pytest',
            args=None,
            exc_info=sys.exc_info()
        ))

    slacker_mock.return_value.chat.post_message.assert_called_once_with(
        text=None,
        channel='#pytest',
        username=SlackHandler.DEFAULT_USERNAME,
        icon_url=None,
        icon_emoji=SlackHandler.DEFAULT_EMOJI,
        attachments=[{
            'color': 'danger',
            'fields': [{
                'title': 'LogRecord from pytest',
                'short': False,
                'value': '```Exception: EXCEPTION RAISED ON PURPOSE!\n```'
            }]
        }]
    ) 
Example 47
Project: flasky   Author: RoseOu   File: log.py    MIT License 5 votes vote down vote up
def error(self, msg, *args, **kwargs):
        """
        Delegate an error call to the underlying logger.
        """
        self.log(logging.ERROR, msg, *args, **kwargs) 
Example 48
Project: flasky   Author: RoseOu   File: log.py    MIT License 5 votes vote down vote up
def exception(self, msg, *args, **kwargs):
        """Delegate an exception call to the underlying logger."""

        kwargs["exc_info"] = 1
        self.log(logging.ERROR, msg, *args, **kwargs) 
Example 49
Project: flasky   Author: RoseOu   File: log.py    MIT License 5 votes vote down vote up
def error(self, msg, *args, **kw):
        self.log(self.ERROR, msg, *args, **kw) 
Example 50
Project: core   Author: lifemapper   File: log.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, isDev=False):
        if isDev:
            level = logging.DEBUG
        else:
            level = logging.ERROR
        LmServerLogger.__init__(self, 'map', level=level, addFile=True)

# .............................................................................