python - 当未使用 Colorama 显式指定颜色时,无法以默认颜色打印日志

标签 python logging colorama

我正在尝试使用 python 中的 colorama 和日志记录模块来获取彩色日志。 如果我没有给出任何颜色,那么它应该打印默认的终端颜色,但在我的日志中,如果没有明确设置颜色,我将获得先前设置的日志的颜色。

下面是我的 setup_logging.yml 文件

import os
import yaml
import logging.config


def setup_logging(
    default_path='logging.yml', default_level=logging.INFO, env_key='LOG_CFG'):
path = os.path.join('/etc', 'module', default_path)
    value = os.getenv(env_key, None)
if value:
    path = value
if os.path.exists(path):
    with open(path, 'rt') as f:
        config = yaml.load(f.read())
    logging.config.dictConfig(config)
else:
    logging.basicConfig(level=default_level)

Logging.yml 文件

 version: 1

 disable_existing_loggers: True 


formatters:
   default:
    format:  "%(asctime)s - %(name)s - %(levelname)s - \n %(message)s"
handlers:
   console:
    class: logging.StreamHandler
    level: INFO 
    formatter: default
    stream: ext://sys.stdout

info_file_handler:
    class: logging.handlers.RotatingFileHandler
    level: INFO
    formatter: default
    filename: /var/log/jsnapy/test.log
    maxBytes: 10485760 # 10MB
    backupCount: 20
    encoding: utf8

我已经删除了日志功能的代码:

 import logging
 import colorama

class Test:

def __init__(self):
    self.logger = logging.getLogger(__name__)
    colorama.init(autoreset=True)
    setup_logging.setup_logging()

def testing(self):
    self.logger.debug(colorama.Fore.RED + "this is a debugging message")
    self.logger.info(colorama.Fore.BLUE+"this is an informational message")
    self.logger.warn(colorama.Fore.BLUE+"this is a warning message")
    self.logger.error(colorama.Fore.YELLOW +  "this is an error message")
    self.logger.critical("this is a critical message")

t = Test()
t.testing()

未明确指定颜色时如何获取日志中的默认颜色。

最佳答案

您需要使用 init(autoreset=True) 来实现此目的,如官方文档中所述:

If you find yourself repeatedly sending reset sequences to turn off color changes at the end of every print, then init(autoreset=True) will automate that:

from colorama import init
init(autoreset=True)
print(Fore.RED + 'some red text')
print('automatically back to default color again')

关于python - 当未使用 Colorama 显式指定颜色时,无法以默认颜色打印日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36793180/

相关文章:

c# - 以数据库为存储介质在.NET中实现日志记录库

python - py2exe;导入错误没有名为 colorama 的模块

python - 不会消失的恼人空间。我应该怎么办?

python - 用条件替换(而不是删除)一个字符

python - 在 Python 中重写 logging.Formatter

python - 我应该如何在 Django 中编写 View 单元测试?

Python 捕获 stdout/stderr 并在查看输出时记录到文件

python - IO错误 : [Errno 0] Error while writing to output of Powershell in VSCode

python - 按列表中元素的出现次数对列表进行排序

python - Django python paypalrestsdk - 没有 'Access-Control-Allow-Origin' 和 ppxo_unhandled_error 错误