8

我正在尝试设置一个记录器格式化程序,在显示消息之前去除任何前导 '\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
4

3 回答 3

12

因为您正在修改输入消息本身,所以您需要子类化logging.Formatter

class WhitespaceRemovingFormatter(logging.Formatter):
    def format(self, record):
        record.msg = record.msg.strip()
        return super(WhitespaceRemovingFormatter, self).format(record)
于 2013-11-05T21:20:31.620 回答
-1
def logger(my_str):
    s = my_str.strip()
    print s

logger("\n\ttest")

从文档:

string.strip(s[, chars])

Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

于 2013-07-29T18:31:20.037 回答
-1

使用str.strip()方法:

>>> s= "\n\rrohit\n"
>>> s.strip()
'rohit'
于 2013-07-29T18:26:03.590 回答