def new_client(client, svr): opened_files = {} while True: for root, dirs, files in os.walk(os.getenv('LOCAL_PATH')): for f in files: if f.endswith('_color') and os.getenv( 'TEST_NAME') in root: if not opened_files.get(f): opened_files[f] = open(join(root, f)) log_lines = [ convert(l) for l in opened_files[f].readlines() ] if log_lines != []: node = splitext(f)[0].split('_') node_num = node[-1] if node[-1].isdigit( ) else None node_type = node[:-1] if node[-1].isdigit( ) else node svr.send_message_to_all( json.dumps({ 'node_type': '_'.join(node_type), 'node_num': node_num, 'log_lines': log_lines })) time.sleep(0.01)
def coloredLoggerTest(): import coloredlogs import verboselogs verboselogs.install() coloredlogs.install( level='SPAM', style='{', fmt=logRecordFormat, datefmt=logDateFormat, level_styles=msgsStyle, field_styles=fieldsStyle, ) if not sys.stdout.isatty(): colorama.deinit() logger = logging.getLogger("Test") logger.spam("SPAM") logger.debug("DEBUG") logger.verbose("VERBOSE") logger.info("INFO") logger.notice("NOTICE") logger.warning("WARNING") logger.success("SUCCESS") logger.error("ERROR") logger.critical("CRITICAL") print("PRINT") from coloredlogs import converter print(converter.convert('\x1b[34mTEXT\x1b[0m', code=False))
def new_client(cli, svr): opened_files = {} try: while True: for root, dirs, files in os.walk(project_path): for f in files: if f.endswith('_color') and test_name in root: if not opened_files.get(f): opened_files[f] = open(join(root, f)) log_lines = [ convert(l) for l in opened_files[f].readlines() ] if log_lines != []: node = splitext(f)[0].split('_') node_num = node[-1] if node[-1].isdigit( ) else None node_type = node[:-1] if node[-1].isdigit( ) else node svr.send_message_to_all( json.dumps({ 'node_type': '_'.join(node_type), 'node_num': node_num, 'log_lines': log_lines })) time.sleep(0.01) except: for f in opened_files: opened_files[f].close()
def test_html_conversion(self): """Check the conversion from ANSI escape sequences to HTML.""" ansi_encoded_text = 'I like %s - www.eelstheband.com' % ansi_wrap('birds', bold=True, color='blue') assert ansi_encoded_text == 'I like \x1b[1;34mbirds\x1b[0m - www.eelstheband.com' html_encoded_text = convert(ansi_encoded_text) assert html_encoded_text == ( 'I like <span style="font-weight: bold; color: blue;">birds</span> - ' '<a href="http://www.eelstheband.com" style="color: inherit;">www.eelstheband.com</a>' )
def convert_command_output(*command): """ Command line interface for ``coloredlogs --to-html``. Takes a command (and its arguments) and runs the program under ``script`` (emulating an interactive terminal), intercepts the output of the command and converts ANSI escape sequences in the output to HTML. """ html_output = convert(capture(command)) if connected_to_terminal(): fd, temporary_file = tempfile.mkstemp(suffix='.html') with open(temporary_file, 'w') as handle: handle.write(html_output) webbrowser.open(temporary_file) else: print(html_output)
def capture_html(capturer, sample_file): """Convert a command's output to HTML and use that to update a sample output file.""" html_text = convert(u"\n".join( line for line in capturer.get_lines() # Ignore lots of boring apt-get output. # if line[:4].isdigit() )) # Replace <br> elements with newline characters. html_text = re.sub(ur'\s*<\s*[Bb][Rr]\s*/?\s*>\s*', ur'\n', html_text) # Replace non-breaking spaces that are surrounded by non-whitespace # characters with regular spaces (to improve text wrapping). html_text = re.sub(ur'(\S) (\S)', ur'\1 \2', html_text) # Wrap the terminal output in a pre-formatted text block. html_text = u"<pre>%s</pre>\n" % html_text.strip() with codecs.open(sample_file, 'w', 'UTF-8') as handle: handle.write(html_text)
def test_html_conversion(self): """Check the conversion from ANSI escape sequences to HTML.""" # Check conversion of colored text. for color_name, ansi_code in ANSI_COLOR_CODES.items(): ansi_encoded_text = 'plain text followed by %s text' % ansi_wrap(color_name, color=color_name) expected_html = format( '<code>plain text followed by <span style="color:{css}">{name}</span> text</code>', css=EIGHT_COLOR_PALETTE[ansi_code], name=color_name, ) self.assertEqual(expected_html, convert(ansi_encoded_text)) # Check conversion of bright colored text. expected_html = '<code><span style="color:#FF0">bright yellow</span></code>' self.assertEqual(expected_html, convert(ansi_wrap('bright yellow', color='yellow', bright=True))) # Check conversion of text with a background color. expected_html = '<code><span style="background-color:#DE382B">red background</span></code>' self.assertEqual(expected_html, convert(ansi_wrap('red background', background='red'))) # Check conversion of text with a bright background color. expected_html = '<code><span style="background-color:#F00">bright red background</span></code>' self.assertEqual(expected_html, convert(ansi_wrap('bright red background', background='red', bright=True))) # Check conversion of text that uses the 256 color mode palette as a foreground color. expected_html = '<code><span style="color:#FFAF00">256 color mode foreground</span></code>' self.assertEqual(expected_html, convert(ansi_wrap('256 color mode foreground', color=214))) # Check conversion of text that uses the 256 color mode palette as a background color. expected_html = '<code><span style="background-color:#AF0000">256 color mode background</span></code>' self.assertEqual(expected_html, convert(ansi_wrap('256 color mode background', background=124))) # Check that invalid 256 color mode indexes don't raise exceptions. expected_html = '<code>plain text expected</code>' self.assertEqual(expected_html, convert('\x1b[38;5;256mplain text expected\x1b[0m')) # Check conversion of bold text. expected_html = '<code><span style="font-weight:bold">bold text</span></code>' self.assertEqual(expected_html, convert(ansi_wrap('bold text', bold=True))) # Check conversion of underlined text. expected_html = '<code><span style="text-decoration:underline">underlined text</span></code>' self.assertEqual(expected_html, convert(ansi_wrap('underlined text', underline=True))) # Check conversion of strike-through text. expected_html = '<code><span style="text-decoration:line-through">strike-through text</span></code>' self.assertEqual(expected_html, convert(ansi_wrap('strike-through text', strike_through=True))) # Check conversion of inverse text. expected_html = '<code><span style="background-color:#FFC706;color:#000">inverse</span></code>' self.assertEqual(expected_html, convert(ansi_wrap('inverse', color='yellow', inverse=True))) # Check conversion of URLs. for sample_text in 'www.python.org', 'http://coloredlogs.rtfd.org', 'https://coloredlogs.rtfd.org': sample_url = sample_text if '://' in sample_text else ('http://' + sample_text) expected_html = '<code><a href="%s" style="color:inherit">%s</a></code>' % (sample_url, sample_text) self.assertEqual(expected_html, convert(sample_text)) # Check that the capture pattern for URLs doesn't match ANSI escape # sequences and also check that the short hand for the 0 reset code is # supported. These are tests for regressions of bugs found in # coloredlogs <= 8.0. reset_short_hand = '\x1b[0m' blue_underlined = ansi_style(color='blue', underline=True) ansi_encoded_text = '<%shttps://coloredlogs.readthedocs.io%s>' % (blue_underlined, reset_short_hand) expected_html = ( '<code><<span style="color:#006FB8;text-decoration:underline">' '<a href="https://coloredlogs.readthedocs.io" style="color:inherit">' 'https://coloredlogs.readthedocs.io' '</a></span>></code>' ) self.assertEqual(expected_html, convert(ansi_encoded_text))
def test_html_conversion(self): """Check the conversion from ANSI escape sequences to HTML.""" # Check conversion of colored text. for color_name, ansi_code in ANSI_COLOR_CODES.items(): ansi_encoded_text = 'plain text followed by %s text' % ansi_wrap(color_name, color=color_name) expected_html = format( '<code>plain text followed by <span style="color:{css}">{name}</span> text</code>', css=EIGHT_COLOR_PALETTE[ansi_code], name=color_name, ) self.assertEquals(expected_html, convert(ansi_encoded_text)) # Check conversion of bright colored text. expected_html = '<code><span style="color:#FF0">bright yellow</span></code>' self.assertEquals(expected_html, convert(ansi_wrap('bright yellow', color='yellow', bright=True))) # Check conversion of text with a background color. expected_html = '<code><span style="background-color:#DE382B">red background</span></code>' self.assertEquals(expected_html, convert(ansi_wrap('red background', background='red'))) # Check conversion of text with a bright background color. expected_html = '<code><span style="background-color:#F00">bright red background</span></code>' self.assertEquals(expected_html, convert(ansi_wrap('bright red background', background='red', bright=True))) # Check conversion of text that uses the 256 color mode palette as a foreground color. expected_html = '<code><span style="color:#FFAF00">256 color mode foreground</span></code>' self.assertEquals(expected_html, convert(ansi_wrap('256 color mode foreground', color=214))) # Check conversion of text that uses the 256 color mode palette as a background color. expected_html = '<code><span style="background-color:#AF0000">256 color mode background</span></code>' self.assertEquals(expected_html, convert(ansi_wrap('256 color mode background', background=124))) # Check that invalid 256 color mode indexes don't raise exceptions. expected_html = '<code>plain text expected</code>' self.assertEquals(expected_html, convert('\x1b[38;5;256mplain text expected\x1b[0m')) # Check conversion of bold text. expected_html = '<code><span style="font-weight:bold">bold text</span></code>' self.assertEquals(expected_html, convert(ansi_wrap('bold text', bold=True))) # Check conversion of underlined text. expected_html = '<code><span style="text-decoration:underline">underlined text</span></code>' self.assertEquals(expected_html, convert(ansi_wrap('underlined text', underline=True))) # Check conversion of strike-through text. expected_html = '<code><span style="text-decoration:line-through">strike-through text</span></code>' self.assertEquals(expected_html, convert(ansi_wrap('strike-through text', strike_through=True))) # Check conversion of inverse text. expected_html = '<code><span style="background-color:#FFC706;color:#000">inverse</span></code>' self.assertEquals(expected_html, convert(ansi_wrap('inverse', color='yellow', inverse=True))) # Check conversion of URLs. for sample_text in 'www.python.org', 'http://coloredlogs.rtfd.org', 'https://coloredlogs.rtfd.org': sample_url = sample_text if '://' in sample_text else ('http://' + sample_text) expected_html = '<code><a href="%s" style="color:inherit">%s</a></code>' % (sample_url, sample_text) self.assertEquals(expected_html, convert(sample_text)) # Check that the capture pattern for URLs doesn't match ANSI escape # sequences and also check that the short hand for the 0 reset code is # supported. These are tests for regressions of bugs found in # coloredlogs <= 8.0. reset_short_hand = '\x1b[0m' blue_underlined = ansi_style(color='blue', underline=True) ansi_encoded_text = '<%shttps://coloredlogs.readthedocs.io%s>' % (blue_underlined, reset_short_hand) expected_html = ( '<code><<span style="color:#006FB8;text-decoration:underline">' '<a href="https://coloredlogs.readthedocs.io" style="color:inherit">' 'https://coloredlogs.readthedocs.io' '</a></span>></code>' ) self.assertEquals(expected_html, convert(ansi_encoded_text))
class ColoredFileHandler(logging.FileHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setFormatter(coloredlogs.ColoredFormatter(format)) os.makedirs(filedir, exist_ok=True) filehandlers = [ ColoredFileHandler('{}.color'.format(filename)), logging.StreamHandler() ] logging.basicConfig(format=format, handlers=filehandlers, level=logging.DEBUG) return logging.getLogger(name) coloredlogs.install(level="DEBUG") logger = get_logger('coloredlog') logger.debug("this is a debugging message") logger.info("this is an informational message") logger.warning("this is a warning message") logger.error("this is an error message") logger.critical("this is a critical message") with open('logs/test/coloredlog.log') as f: print('Parsing logs') for line in f: print(convert(line.strip()))
def emit(self, record): s = AnsiToHtmlConverter.convert(self.format(record), code=False) self.logEmittedHtml.emit(s)
def emit(self, record): from coloredlogs import converter s = converter.convert(self.format(record), code=False) print(s) self.logEmittedHtml.emit(s)
def emit(self, record): # Format the record. record = self.format(record) record = converter.convert(record, code=True, tabsize=4) # Add the record to the widget. self.appendLog.emit(record)