#๐Ÿ”’ log to file working, but not to console

6 messages ยท Page 1 of 1 (latest)

honest zealot
#
import logging

class ColoredFormatter(logging.Formatter):
    grey = "\x1b[38;20m"
    yellow = "\x1b[33;20m"
    red = "\x1b[31;20m"
    bold_red = "\x1b[31;1m"
    reset = "\x1b[0m"

    FORMATS = {
        logging.DEBUG: f"%(asctime)s - %(name)s - %(levelname)s - {grey} %(message)s {reset} (%(filename)s:%(lineno)d)",
        logging.INFO: f"%(asctime)s - %(name)s - %(levelname)s - {grey} %(message)s {reset} (%(filename)s:%(lineno)d)",
        logging.WARNING: f"%(asctime)s - %(name)s - %(levelname)s - {yellow} %(message)s {reset} (%(filename)s:%(lineno)d)",
        logging.ERROR: f"%(asctime)s - %(name)s - %(levelname)s - {red} %(message)s {reset} (%(filename)s:%(lineno)d)",
        logging.CRITICAL: f"%(asctime)s - %(name)s - %(levelname)s - {bold_red} %(message)s {reset} (%(filename)s:%(lineno)d)"
    }

    def format(self, record):
        log_fmt = self.FORMATS.get(record.levelno)
        formatter = logging.Formatter(log_fmt)
        return formatter.format(record)

cf = ColoredFormatter()

msg_logger = logging.getLogger("MSG_LOG")
msg_logger.setLevel(logging.INFO)
msg_file_handler = logging.FileHandler("src/log_comms/logs/logs.txt")
msg_file_handler.setFormatter(cf)
msg_logger.addHandler(msg_file_handler)
msg_logger.addHandler(logging.StreamHandler())

Hi there, i currently have this set-up for storing logs. It stores correctly with the file handler:
2024-02-19 23:34:53,328 - MSG_LOG - INFO -  test  (log.py:81)
However,
for the stream handler it just prints:
test
Any reason why would be the case"?

exotic gladeBOT
#

@honest zealot

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

honest zealot
#

ah wait, didnt set the formatter for the stream handler, my bad xd

#
2024-02-19 23:40:26,602 - MSG_LOG - INFO -  test  (log.py:88)

working properly now, not printing any colours though. imma look into this

exotic gladeBOT
#

@honest zealot

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.