写入文件(但不写入标准输出)时,Python日志记录会添加其他换行符

时间:2019-05-17 10:43:27

标签: python logging newline

我在Windows 7上设置了Python(3.6.5)记录器,以同时写入文件和标准输出:

def __filehandler() -> logging.FileHandler:
    filehandler = logging.FileHandler(LOGFILE, encoding="cp932")
    filehandler.setLevel(logging.DEBUG)
    fformatter = logging.Formatter("%(asctime)s: %(name)-13s: %(levelname)-8s: %(message)s")
    filehandler.setFormatter(fformatter)

    return filehandler


def __streamhandler() -> logging.StreamHandler:
    streamhandler = logging.StreamHandler()
    streamhandler.setLevel(logging.DEBUG)
    sformatter = logging.Formatter("%(name)-13s: %(levelname)-8s: %(message)s")
    streamhandler.setFormatter(sformatter)

    return streamhandler


def getlogger(calling_module_name: str) -> logging.Logger:
    logger = logging.getLogger(calling_module_name)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(__filehandler())
    logger.addHandler(__streamhandler())

    return logger

然后使用它调用logger.info(some_text)

标准输出看起来像预期的

mymodule: INFO    : Reading file #1/2, line #42/164: /****************************************************************************/
mymodule: INFO    : Writing file #1/2, line #42/164: /****************************************************************************/
mymodule: INFO    : Reading file #1/2, line #43/164:
mymodule: INFO    : Writing file #1/2, line #43/164:
mymodule: INFO    : Reading file #1/2, line #44/164:
mymodule: INFO    : Writing file #1/2, line #44/164:

但是在相应的文件中,还有其他内容,但不包含换行符

2019-05-17 12:21:11,824: mymodule: INFO    : Reading file #1/2, line #42/164: /****************************************************************************/

2019-05-17 12:21:11,824: mymodule: INFO    : Writing file #1/2, line #42/164: /****************************************************************************/
2019-05-17 12:21:11,824: mymodule: INFO    : Reading file #1/2, line #43/164: 

2019-05-17 12:21:11,824: mymodule: INFO    : Writing file #1/2, line #43/164: 

2019-05-17 12:21:11,824: mymodule: INFO    : Reading file #1/2, line #44/164: 

2019-05-17 12:21:11,839: mymodule: INFO    : Writing file #1/2, line #44/164: 

filehandler = logging.FileHandler(LOGFILE, encoding="cp932")更改为filehandler = logging.FileHandler(LOGFILE)无效。

添加的换行符不利于日志的清晰度,并不必要地夸大了日志的大小。任何想法在这里发生了什么?

0 个答案:

没有答案