有没有可能让日志模块在写入日志时修复行尾

2024-10-03 09:09:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用日志模块将字符串写入日志文件。是否可以将所有行尾转换为'\n'。来自不同位置的输出可能有\r\n或\r\n,并且我希望写入日志的所有内容都有一致的行尾。像这样:

class Logger():
    def __init__( self, path ):
        msgFormat   = '%(asctime)s.%(msecs)d\t%(message)s'
        dateFormat  = '%m/%d/%Y %H:%M:%S'
        logging.basicConfig( format=msgFormat, datefmt=dateFormat, filename=path, level=logging.INFO )

    def Log ( self, theStr ):
        logging.info( str( theStr ))

然后我创建一个具有有效路径的记录器,Pexpect的输出类似于b'Line One\r\nLine Two'。所以我解码()并将其发送到Log()

result = b'Line One\r\nLine Two'
theLog.Log( result.decode( ))

Tags: 模块pathselflogloggingdeflineresult
1条回答
网友
1楼 · 发布于 2024-10-03 09:09:31

这可以通过添加自己的格式化程序来完成。在这一点上,可能更容易不再使用basicConfig,因为我们需要做非基本的事情。日志行都将以\n结束,因为这是FileHandler使用的默认终止符。如果您想要其他的东西,请添加handler.terminator='\r\n'或任何首选的行尾。你知道吗

import logging

class NewLineFormatter(logging.Formatter):
    def format(self, record):
        msg = super().format(record)
        return msg.rstrip() # removes trailing newlines (and other whitespace)

class Logger():
    def __init__(self, path):
        msgFormat   = '%(asctime)s.%(msecs)d\t%(message)s'
        dateFormat  = '%m/%d/%Y %H:%M:%S'
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)
        handler = logging.FileHandler(path)
        handler.setFormatter(NewLineFormatter(msgFormat, dateFormat))
        logger.addHandler(handler)
        self.logger = logger

    def Log(self, the_str):
        self.logger.info(the_str)

l = Logger('test.log')
l.Log('test\r\n')

相关问题 更多 >