我正在尝试使用 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/