I'm trying to setup a logger formatter that strips any leading '\n' or '\t' characters before displaying the message.
Is there a way to do this by setting up a logger filter?
EDIT: I understand I should str.strip(), but how can I integrate this with the logger for every message?
Here's an example of my logger setup:
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
Because you're modifying the input message itself, you need to subclass logging.Formatter
class WhitespaceRemovingFormatter(logging.Formatter):
def format(self, record):
record.msg = record.msg.strip()
return super(WhitespaceRemovingFormatter, self).format(record)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With