Reputation: 7887
A little context to what I am doing. I am running some python scripts through a different programming language on an industrial controller. Since I am not running the python scripts directly I can't watch any print or log statements from the terminal so I need to send the detailed logs to a log file.
Since we are logging a lot of information when debugging, I wanted to find a way to color the log file such as coloredlogs
does to logs printed to terminal. I looked at coloredlogs
but it appears that it can only print colored logs to files when using VIM
. Does anyone know a way to print colored logs to a file using python that can be opened with a program such as wordpad? (maybe a .rtf
file).
Upvotes: 2
Views: 7917
Reputation: 6474
It can be a solution to use the Windows PowerShell
Get-Content
function to print a file which contains ANSI escape sequences
to color the log.
For example:
import coloredlogs
import logging
# Create a logger object.
logger = logging.getLogger(__name__)
# Create a filehandler object
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# Create a ColoredFormatter to use as formatter for the FileHandler
formatter = coloredlogs.ColoredFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
# Install the coloredlogs module on the root logger
coloredlogs.install(level='DEBUG')
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")
When opening a Windows PowerShell
you can use Get-Content .\spam.log
to print the logs in color.
Upvotes: 2