从Python Logger消息中删除换行符和空格

时间:2013-07-29 18:24:36

标签: python logging

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

3 个答案:

答案 0 :(得分:5)

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

class WhitespaceRemovingFormatter(logging.Formatter):
    def format(self, record):
        record.msg = record.msg.strip()
        return super(WhitespaceRemovingFormatter, self).format(record)

答案 1 :(得分:0)

使用str.strip()方法:

>>> s= "\n\rrohit\n"
>>> s.strip()
'rohit'

答案 2 :(得分:0)

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.