【问题标题】:Python Logging, Not Writing Timestamp to Output FilePython 日志记录,不将时间戳写入输出文件
【发布时间】:2015-11-06 12:59:27
【问题描述】:

我正在使用以下语句创建日志:

module = sys.modules['__main__'].__file__
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG,
                format='%(asctime)s %(name)s (%(levelname)s): %(message)s')
log = logging.getLogger(module)

然后,我的脚本上有一个选项,可以使用参数 -o 将输出写入文件。我认为当一个人指定他们希望将日志写入磁盘时,会出现此语句的问题:

 if arguments.o:
    fh = RotatingFileHandler(arguments.o, mode='a', maxBytes=2*1024*1024,
                        backupCount=2, encoding=None, delay=0)
    fh.setLevel(logging.DEBUG)
    log.addHandler(fh)

如果不向文本字符串添加额外的日期时间语句,有没有办法使用格式参数来做到这一点?

这是打印出来的:

2015-11-06 07:27:13,592 C:\GIS\move_content\src\updatecontent.py (INFO): Reading Configuration file

这是配置输出:

Reading Configuration file

谢谢

我找到的答案:

根据我的一个响应,我能够将其添加到我的代码中,现在输出看起来正确:

# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

【问题讨论】:

    标签: python-2.7 logging


    【解决方案1】:

    文件处理程序使用不同的格式字符串,您也应该手动将其设置为文件处理程序。

    例子:

    fh.setFormatter(formatter)
    

    Cookbook for Python 3 (Python 2 is the same for this question)

    【讨论】:

    • @Penguinlog - 你能提供一个设置文件处理程序日志的例子吗?
    • 那么设置setFormater()你不传入一个字符串? '%(asctime)s %(name)s (%(levelname)s): %(message)s'
    • 答案是:# 创建格式化程序并将其添加到处理程序 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message )s') fh.setFormatter(格式化程序)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 2019-03-14
    • 2015-12-29
    • 1970-01-01
    • 2021-12-19
    • 2017-11-09
    相关资源
    最近更新 更多