【问题标题】:How to save log file using Python?如何使用 Python 保存日志文件?
【发布时间】:2019-12-12 20:24:53
【问题描述】:

我有一个 powershell 脚本,我用这种方式保存日志

$Log = Start-Transcript -Path $Log_Path -Force

如何在 Python 中使用它?

【问题讨论】:

标签: python


【解决方案1】:

您可以使用以下命令写入/保存日志文件。

logging.basicConfig(filename='path to the log file', level=...)

有一个文件模式选项可以覆盖文件。 要覆盖你可以指定文件模式:w

logging.basicConfig(filename='logs.log',
            filemode='w',
            level=logging.INFO)

filemode:指定打开文件的模式,如果指定了filename(如果未指定filemode,则默认为'a')。

【讨论】:

  • 这样我可以将日志保存到文件中,但不会覆盖日志,如何让它覆盖?
  • 只需添加 filemode:w 即可覆盖文件。
【解决方案2】:

python中有一个日志模块。你可以导入一个使用那个。

import logging logging.basicConfig(level=logging.DEBUG) logging.debug('This will get logged')

输出将是:

DEBUG:root:This will get logged

同样,您也可以使用其他日志级别。你可以找到更多关于它here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2022-11-03
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多