我正在尝试设置一个记录器格式化程序,在显示消息之前去除任何前导 '\n' 或 '\t' 字符。
有没有办法通过设置记录器过滤器来做到这一点?
编辑:我知道我应该 str.strip(),但是如何将它与每条消息的记录器集成?
这是我的记录器设置的示例:
def initialize_logging(log_dir='Logs', log_name='log.log',
console_level='INFO', file_level='DEBUG'):
start_time = datetime.datetime.now()
start_time_string= start_time.strftime("%m-%d-%y_%Hh%Mm%Ss")
if file_level == "DEBUG":
level = logging.DEBUG
elif file_level == "INFO":
level = logging.INFO
elif file_level == "WARNING":
level = logging.WARNING
elif file_level == "ERROR":
level = logging.ERROR
elif file_level == "CRITICAL":
level = logging.CRITICAL
else:
level = logging.INFO
log = logging.getLogger()
log.setLevel(level)
#create a log formatter
formatter = logging.Formatter('%(asctime)s %(name)-24s: %(levelname)-8s: %(message)s','%m-%d-%y %H:%M:%S')
#create log handlers
#console handler
console = logging.StreamHandler()
if console_level == "DEBUG":
console.setLevel(logging.DEBUG)
elif console_level == "INFO":
console.setLevel(logging.INFO)
elif console_level == "WARNING":
console.setLevel(logging.WARNING)
elif console_level == "ERROR":
console.setLevel(logging.ERROR)
elif console_level == "CRITICAL":
console.setLevel(logging.CRITICAL)
else:
console.setLevel(logging.INFO)
console.setFormatter(formatter)
log.addHandler(console)
log_path = str(os.getcwd()) + '/Logs/'
if not os.path.exists(log_path):
os.makedirs(log_path)
log_file_name = 'last.log'
log_file = os.path.join(log_path, log_file_name)
logfile = logging.FileHandler(log_file, "w")
if file_level == "DEBUG":
logfile.setLevel(logging.DEBUG)
elif file_level == "INFO":
logfile.setLevel(logging.INFO)
elif file_level == "WARNING":
logfile.setLevel(logging.WARNING)
elif file_level == "ERROR":
logfile.setLevel(logging.ERROR)
elif file_level == "CRITICAL":
logfile.setLevel(logging.CRITICAL)
else:
logfile.setLevel(logging.INFO)
logfile.setFormatter(formatter)
log.addHandler(logfile)
return log #return a path to the log file