Exemplo n.º 1
0
 def test_program_name_filter(self):
     """Make sure :func:`install()` integrates with :class:`~colouredlogs.ProgramNameFilter()`."""
     install(fmt='%(programname)s')
     with CaptureOutput() as capturer:
         logging.info("A truly insignificant message ..")
         output = capturer.get_text()
         assert find_program_name() in output
Exemplo n.º 2
0
 def test_plain_text_output_format(self):
     """Inspect the plain text output of colouredlogs."""
     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 test_colorama_enabled(self):
     """Test that colorama is enabled (through mocking)."""
     init_function = MagicMock()
     with mocked_colorama_module(init_function):
         # Configure logging to the terminal.
         colouredlogs.install()
         # Ensure that our mock method was called.
         assert init_function.called
Exemplo n.º 4
0
def get_logger(name):
    logger = logging.getLogger(name)
    colouredlogs.install(
        logger=logger,
        level=logging.WARN,
        stream=sys.stdout,
        datefmt='%H:%M:%S',
    )
    return logger
Exemplo n.º 5
0
 def test_support_for_milliseconds_directive(self):
     """Make sure milliseconds using the ``%f`` directive are supported."""
     stream = StringIO()
     install(reconfigure=True,
             stream=stream,
             datefmt='%Y-%m-%dT%H:%M:%S.%f%z')
     logging.info("This should be timestamped according to #45.")
     assert re.match(
         r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}(\+|-)\d{4}\s',
         stream.getvalue())
Exemplo n.º 6
0
 def test_syslog_shortcut_simple(self):
     """Make sure that ``colouredlogs.install(syslog=True)`` works."""
     system_log_file = self.find_system_log()
     expected_message = random_string(50)
     with cleanup_handlers():
         # See test_system_logging() for the importance of this log level.
         colouredlogs.install(syslog=True)
         logging.error("%s", expected_message)
     # See the comments in test_system_logging() on why this is retried.
     retry(lambda: check_contents(system_log_file, expected_message, True))
Exemplo n.º 7
0
 def test_syslog_shortcut_enhanced(self):
     """Make sure that ``colouredlogs.install(syslog='warning')`` works."""
     system_log_file = self.find_system_log()
     the_expected_message = random_string(50)
     not_an_expected_message = random_string(50)
     with cleanup_handlers():
         # See test_system_logging() for the importance of these log levels.
         colouredlogs.install(syslog='error')
         logging.warning("%s", not_an_expected_message)
         logging.error("%s", the_expected_message)
     # See the comments in test_system_logging() on why this is retried.
     retry(lambda: check_contents(system_log_file, the_expected_message,
                                  True))
     retry(lambda: check_contents(system_log_file, not_an_expected_message,
                                  False))
Exemplo n.º 8
0
 def test_support_for_milliseconds(self):
     """Make sure milliseconds are hidden by default but can be easily enabled."""
     # Check that the default log format doesn't include milliseconds.
     stream = StringIO()
     install(reconfigure=True, stream=stream)
     logging.info("This should not include milliseconds.")
     assert all(
         map(PLAIN_TEXT_PATTERN.match,
             stream.getvalue().splitlines()))
     # Check that milliseconds can be enabled via a shortcut.
     stream = StringIO()
     install(milliseconds=True, reconfigure=True, stream=stream)
     logging.info("This should include milliseconds.")
     assert all(
         map(PATTERN_INCLUDING_MILLISECONDS.match,
             stream.getvalue().splitlines()))
def main():
    """Command line interface."""
    colouredlogs.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.
        """))
        generate_screenshots()
Exemplo n.º 10
0
    def test_colorama_missing(self):
        """Test that colorama is missing (through mocking)."""
        def init_function():
            raise ImportError

        with mocked_colorama_module(init_function):
            # Configure logging to the terminal. It is expected that internally
            # an ImportError is raised, but the exception is caught and coloured
            # output is disabled.
            colouredlogs.install()
            # Find the handler that was created by colouredlogs.install().
            handler, logger = find_handler(logging.getLogger(),
                                           match_stream_handler)
            # Make sure that logging to the terminal was initialized.
            assert isinstance(handler.formatter, logging.Formatter)
            # Make sure coloured logging is disabled.
            assert not isinstance(handler.formatter, ColouredFormatter)
Exemplo n.º 11
0
def demonstrate_coloured_logging():
    """Interactively demonstrate the :mod:`colouredlogs` package."""
    # Determine the available logging levels and order them by numeric value.
    decorated_levels = []
    defined_levels = colouredlogs.find_defined_levels()
    normalizer = colouredlogs.NameNormalizer()
    for name, level in defined_levels.items():
        if name != 'NOTSET':
            item = (level, normalizer.normalize_name(name))
            if item not in decorated_levels:
                decorated_levels.append(item)
    ordered_levels = sorted(decorated_levels)
    # Initialize coloured output to the terminal, default to the most
    # verbose logging level but enable the user the customize it.
    colouredlogs.install(
        level=os.environ.get('COLOUREDLOGS_LOG_LEVEL', ordered_levels[0][1]))
    # Print some examples with different timestamps.
    for level, name in ordered_levels:
        log_method = getattr(logger, name, None)
        if log_method:
            log_method("message with level %s (%i)", name, level)
            time.sleep(DEMO_DELAY)
Exemplo n.º 12
0
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import datetime
import json
import logging

import colouredlogs
import discord
from discord.ext import commands
from motor.motor_asyncio import AsyncIOMotorClient

from ext.checks import NoMod, NoSomething
from ext.context import EditingContext

colouredlogs.install()

with open("settings.json") as content:
    settings = json.load(content)

logging.basicConfig(level=logging.INFO)
logging.getLogger("discord").setLevel(logging.WARNING)

logging.info("Starting bot")
db = AsyncIOMotorClient(settings["mongo"]["uri"])[settings["mongo"]["db"]]
botExtensions = [
    "cogs.help", "cogs.utility", "cogs.tickets", "cogs.tags", "cogs.notes",
    "cogs.admin", "jishaku"
]

Exemplo n.º 13
0
import tabulate
import zmq

from nem.share import CODE, SOCK
"""
COMMAND CODE

COMMAND PWD TIMESTAMP
"""
DATABASE = 'db'

log = logging.getLogger(__name__)
colouredlogs.install(
    logger=log,
    level=logging.INFO,
    stream=sys.stdout,
    format=
    '%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
    datefmt='%H:%M:%S',
)
connection = None
cursor = None
context = None
sock = None


class PlsException(Exception):
    pass


class ExitInterrupt(PlsException):
    pass