Exemplo n.º 1
0
 def test_plain_text_output_format(self):
     """Inspect the plain text output of coloredlogs."""
     logger = VerboseLogger(random_string(25))
     stream = StringIO()
     install(level=logging.NOTSET, logger=logger, stream=stream)
     # Test that filtering on severity works.
     logger.setLevel(logging.INFO)
     logger.debug("No one should see this message.")
     assert len(stream.getvalue().strip()) == 0
     # Test that the default output format looks okay in plain text.
     logger.setLevel(logging.NOTSET)
     for method, severity in ((logger.debug, 'DEBUG'), (logger.info,
                                                        'INFO'),
                              (logger.verbose, 'VERBOSE'), (logger.warning,
                                                            'WARN'),
                              (logger.error, 'ERROR'), (logger.critical,
                                                        'CRITICAL')):
         # Prepare the text.
         text = "This is a message with severity %r." % severity.lower()
         # Log the message with the given severity.
         method(text)
         # Get the line of output generated by the handler.
         output = stream.getvalue()
         lines = output.splitlines()
         last_line = lines[-1]
         assert text in last_line
         assert severity in last_line
         assert PLAIN_TEXT_PATTERN.match(last_line)
Exemplo n.º 2
0
 def test_plain_text_output_format(self):
     """Inspect the plain text output of coloredlogs."""
     logger = VerboseLogger(random_string(25))
     stream = StringIO()
     install(level=logging.NOTSET, logger=logger, stream=stream)
     # Test that filtering on severity works.
     logger.setLevel(logging.INFO)
     logger.debug("No one should see this message.")
     assert len(stream.getvalue().strip()) == 0
     # Test that the default output format looks okay in plain text.
     logger.setLevel(logging.NOTSET)
     for method, severity in ((logger.debug, 'DEBUG'),
                              (logger.info, 'INFO'),
                              (logger.verbose, 'VERBOSE'),
                              (logger.warning, 'WARNING'),
                              (logger.error, 'ERROR'),
                              (logger.critical, 'CRITICAL')):
         # Prepare the text.
         text = "This is a message with severity %r." % severity.lower()
         # Log the message with the given severity.
         method(text)
         # Get the line of output generated by the handler.
         output = stream.getvalue()
         lines = output.splitlines()
         last_line = lines[-1]
         assert text in last_line
         assert severity in last_line
         assert PLAIN_TEXT_PATTERN.match(last_line)
Exemplo n.º 3
0
def init_logging(logfile: Path) -> VerboseLogger:
    dev_sync_logger = VerboseLogger(NAME)

    logfile.parent.mkdir(exist_ok=True, parents=True)

    coloredlogs.install(level="DEBUG",
                        milliseconds=True,
                        logger=dev_sync_logger)
    dev_sync_logger.setLevel(logging.DEBUG)

    fh = TimedRotatingFileHandler(logfile, when="MIDNIGHT")
    fh.setFormatter(logging.Formatter(coloredlogs.DEFAULT_LOG_FORMAT))
    dev_sync_logger.addHandler(fh)

    return dev_sync_logger
Exemplo n.º 4
0
 def test_plain_text_output_format(self):
     """Inspect the plain text output of coloredlogs."""
     logger = VerboseLogger(random_string(25))
     stream = StringIO()
     install(level=logging.NOTSET, logger=logger, stream=stream)
     # Test that filtering on severity works.
     logger.setLevel(logging.INFO)
     logger.debug("No one should see this message.")
     assert len(stream.getvalue().strip()) == 0
     # Test that the default output format looks okay in plain text.
     logger.setLevel(logging.NOTSET)
     for method, severity in ((logger.debug, 'DEBUG'),
                              (logger.info, 'INFO'),
                              (logger.verbose, 'VERBOSE'),
                              (logger.warning, 'WARNING'),
                              (logger.error, 'ERROR'),
                              (logger.critical, 'CRITICAL')):
         # XXX Workaround for a regression in Python 3.7 caused by the
         # Logger.isEnabledFor() method using stale cache entries. If we
         # don't clear the cache then logger.isEnabledFor(logging.DEBUG)
         # returns False and no DEBUG message is emitted.
         try:
             logger._cache.clear()
         except AttributeError:
             pass
         # Prepare the text.
         text = "This is a message with severity %r." % severity.lower()
         # Log the message with the given severity.
         method(text)
         # Get the line of output generated by the handler.
         output = stream.getvalue()
         lines = output.splitlines()
         last_line = lines[-1]
         assert text in last_line
         assert severity in last_line
         assert PLAIN_TEXT_PATTERN.match(last_line)
Exemplo n.º 5
0
    'EncryptedSystem',
    'EncryptedSystemError',
    'HOST_KEYS_FILE',
    'ServerDetails',
    'SystemUnreachableError',
    'UnlockAbortedError',
    'UnsupportedSystemError',
    'find_local_username',
    'get_password_from_store',
    'logger',
    'main',
    'prompt_for_password',
)

# Initialize a logger for this module.
logger = VerboseLogger(__name__)


def main():
    """Command line interface for ``unlock-remote-system``."""
    # Initialize logging to the terminal and system log.
    coloredlogs.install(syslog=True)
    # Parse the command line arguments.
    program_opts = {}
    identity_file = None
    do_shell = False
    do_watch = False
    watch_all = False
    try:
        options, arguments = getopt.gnu_getopt(sys.argv[1:], 'i:k:p:r:swavqh',
                                               [
Exemplo n.º 6
0
except Exception:
    logging.error('Could not import all required modules. '
                  'Please run the following command again:\n\n'
                  '\tpipenv install\n')
    exit()

from pathlib import Path
from time import sleep

import sniper.api as api
import sniper.checkout as checkout
import sniper.constants as const
import sniper.webdriver as webdriver
import sniper.notifications as notify

logger = VerboseLogger(
    'root')  #THIS COMMANDS LOGS WARNINGS, ERRORS, INFOS, ETC....

src_path = Path(
    __file__
).parent  ## logical parent of the path  https://docs.python.org/3/library/pathlib.html
data_path = src_path.parent / 'data'  ## data folder
config_path = src_path.parent / 'config'  ## config folder


def read_json(filename):
    with open(filename, encoding='utf-8') as json_file:
        return json.load(json_file)


def update_sku_file(skus):
    with open(data_path / 'skus.json', 'w+') as f:
Exemplo n.º 7
0
import sys

import coloredlogs
from verboselogs import VerboseLogger

from casserole.utils import pretty_bytes
from casserole.protocol import GEAFrame, ERDCommand, ERDCommandID
from casserole.exceptions import ParsingError, IncompleteReadError

LOGGER = VerboseLogger(__name__)


def parse_data(data: bytes):
    while data:
        skipped = data.index(GEAFrame.START_OF_FRAME)

        if skipped > 0:
            LOGGER.warning("Skipping first %d bytes: %s", skipped,
                           pretty_bytes(data[:skipped]))
            data = data[skipped:]

        # LOGGER.info("Trying to parse              %s", pretty_bytes(data))

        try:
            packet, new_data = GEAFrame.deserialize(data)
        except IncompleteReadError:
            break
        except ParsingError:
            LOGGER.warning("Failed to parse", exc_info=True)
            data = data[1:]
            continue
# Configuration defaults.
FONT_NAME = 'Monaco'
"""The name of the font used in screen shots."""

FONT_SIZE = 14
"""The pixel size of the font used in screen shots."""

TEXT_COLOR = 'white'
"""The default text color used in screen shots."""

BACKGROUND_COLOR = 'black'
"""The default background color used in screen shots."""

# Initialize a logger for this program.
logger = VerboseLogger('screenshot-generator')


def main():
    """Command line interface."""
    coloredlogs.install(level='debug')
    arguments = sys.argv[1:]
    if arguments:
        interpret_script(arguments[0])
    else:
        logger.notice(compact("""
            This script requires the 'urxvt' terminal emulator and the
            ImageMagick command line programs 'convert' and 'import' to be
            installed. Don't switch windows while the screenshots are being
            generated because it seems that 'import' can only take screenshots
            of foreground windows.
Exemplo n.º 9
0
        """
        if self.isatty:
            return ansi_text(message, color=colorname, bold=bold)
        else:
            return message

if __name__ == '__main__':

    # If my verbose logger is installed, we'll use that for the demo.
    try:
        from verboselogs import VerboseLogger as DemoLogger
    except ImportError:
        from logging import getLogger as DemoLogger

    # Initialize the logger.
    logger = DemoLogger('coloredlogs-demo')
    logger.addHandler(ColoredStreamHandler())
    logger.setLevel(logging.DEBUG)

    # Print some examples with different timestamps.
    for level in ['debug', 'verbose', 'info', 'warn', 'error', 'critical']:
        if hasattr(logger, level):
            getattr(logger, level)("message with level %r", level)
            time.sleep(1)

    # Show how exceptions are logged.
    try:
        class RandomException(Exception):
            pass
        raise RandomException, "Something went horribly wrong!"
    except Exception, e:
Exemplo n.º 10
0
except Exception:
    logging.error('Could not import all required modules. '
                  'Please run the following command again:\n\n'
                  '\tpipenv install\n')
    exit()

from pathlib import Path
from time import sleep

import sniper.api as api
import sniper.checkout as checkout
import sniper.constants as const
import sniper.webdriver as webdriver
import sniper.notifications as notify

logger = VerboseLogger('root')

src_path = Path(__file__).parent
data_path = src_path.parent / 'data'
config_path = src_path.parent / 'config'


def read_json(filename):
    with open(filename, encoding='utf-8') as json_file:
        return json.load(json_file)


def update_sku_file(skus):
    with open(data_path / 'skus.json', 'w+') as f:
        f.write(json.dumps(skus, indent=4))
Exemplo n.º 11
0
        if self.isatty:
            return ansi_text(message, color=colorname, bold=bold)
        else:
            return message


if __name__ == '__main__':

    # If my verbose logger is installed, we'll use that for the demo.
    try:
        from verboselogs import VerboseLogger as DemoLogger
    except ImportError:
        from logging import getLogger as DemoLogger

    # Initialize the logger.
    logger = DemoLogger('coloredlogs-demo')
    logger.addHandler(ColoredStreamHandler())
    logger.setLevel(logging.DEBUG)

    # Print some examples with different timestamps.
    for level in ['debug', 'verbose', 'info', 'warn', 'error', 'critical']:
        if hasattr(logger, level):
            getattr(logger, level)("message with level %r", level)
            time.sleep(1)

    # Show how exceptions are logged.
    try:

        class RandomException(Exception):
            pass
Exemplo n.º 12
0
        """
        if self.isatty:
            return ansi_text(message, color=colorname, bold=bold)
        else:
            return message

if __name__ == '__main__':

    # If my verbose logger is installed, we'll use that for the demo.
    if HAS_VERBOSELOGS:
        from verboselogs import VerboseLogger as DemoLogger
    else:
        from logging import getLogger as DemoLogger

    # Initialize the logger and handler.
    logger = DemoLogger('coloredlogs-demo')
    install(level=logging.DEBUG)

    # Print some examples with different timestamps.
    for level in ['debug', 'verbose', 'info', 'warn', 'error', 'critical']:
        if hasattr(logger, level):
            getattr(logger, level)("message with level %r", level)
            time.sleep(1)

    # Show how exceptions are logged.
    try:
        class RandomException(Exception):
            pass
        raise RandomException, "Something went horribly wrong!"
    except Exception, e:
        logger.exception(e)