From Terminal to Browser: Rendering ANSI Colored Text in Frontend Pages
This tutorial explains how to convert ANSI escape sequences used for colored logging into HTML so that log output can be securely viewed with proper colors directly in a web browser, including server setup, code examples, and library usage.
Preface
In development we often need to record program state using logs, and using different colors for log levels improves readability. This article demonstrates how to use the Python colorlog library for colored console output and how to render those colors in a web page.
ANSI Escape Sequences
ANSI escape sequences are standardized control codes that can change text color, background, style, cursor position, etc. Examples such as \033[0m (reset), \033[31m (red), \033[42m (green background) are shown.
When logs are written to files the raw escape codes appear (e.g., [32m) because they are ANSI sequences.
Viewing Log Content Directly in the Frontend
Using Python's http.server module a simple HTTP server can be started with python -m http.server 8888. To avoid security issues a whitelist of allowed client IPs is added. The handler overrides do_GET to serve log files when the request path starts with /?log=.
import http.server
import socketserver
class HTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def check_client_address(self):
# 设置白名单,只允许特定的IP地址或主机访问
whitelist = ['127.0.0.1', 'localhost']
client_address = self.client_address[0]
if client_address not in whitelist:
self.send_response(403)
self.end_headers()
self.wfile.write(b'Forbidden. Please contact sidiot.')
return False
return True
def do_GET(self):
if not self.check_client_address():
return
super().do_GET()
with socketserver.TCPServer(('0.0.0.0', 8888), HTTPRequestHandler) as httpd:
httpd.serve_forever()Restoring Colored Text Effect in the Frontend
Principle
Convert ANSI sequences to HTML tags. A Python function maps codes like \x1b[31m to <span style="color:red;">. The function returns HTML that can be inserted into the page.
def convert_ansi_to_html(ansi_text):
ansi_to_html = {
'\x1b[31m': '<span style="color:red;">',
'\x1b[42m': '<span style="background-color:green;">',
# ...
}
html_text = re.sub(r'\x1b[[0-9;]*m', lambda match: ansi_to_html.get(match.group(0), ''), ansi_text)
return html_text
if __name__ == '__main__':
ansi = "\033[42m\033[31mHello World! --sidiot.\033[0m\033[0m"
print(ansi)
html = convert_ansi_to_html(ansi)
print(f"convert content: {html}")Using ansiconv
Install ansiconv via pip install ansiconv and use its to_plain(), to_html(), and base_css() methods to obtain plain text or HTML with CSS classes.
pip install ansiconv import ansiconv
ansi = "\033[42m\033[31mHello World! --sidiot.\033[0m\033[0m"
print(f"Ansi: {ansi}")
plain = ansiconv.to_plain(ansi)
html = ansiconv.to_html(ansi)
print(f"Convert Plain: {plain}")
print(f"Convert HTML: {html}")Source Code Analysis
Shows how to_plain() removes escape sequences with a regular expression, and how to_html() splits the string into blocks and converts each block to HTML, handling newline replacement and cursor movement commands.
Practical Application
Integrates ansiconv into the earlier HTTP server so that /?plain= returns plain text and /?html= returns an HTML page containing the converted ANSI content with appropriate CSS.
<code>def do_GET(self):
if self.check_client_address():
if self.path.startswith("/?plain="):
file = open(self.path[8:], 'rb').read()
plain = ansiconv.to_plain(file.decode('UTF-8'))
self.read_file("text/plain", plain.encode())
elif self.path.startswith("/?html="):
file = open(self.path[7:], 'rb').read()
conv = ansiconv.to_html(file.decode('UTF-8'))
css = ansiconv.base_css()
html = f"""
<html>
<head><style>{css}</style></head>
<body><pre class=\"ansi_fore ansi_back\">{conv}""" self.read_file("text/html", html.encode()) else: super().do_GET()
Conclusion
The article explains how to display ANSI-colored logs in a browser by converting escape sequences to HTML, using either a custom converter or the ansiconv library, and demonstrates a secure Python HTTP server that serves both plain and HTML representations of log files.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
