在 python 日志文件中包含当前日期

发布于 2024-07-29 17:36:07 字数 169 浏览 3 评论 0原文

我有一个每天运行的流程。 它使用 Python 日志记录。 如何配置 python 日志记录模块以写入文件名中包含当前日期的文件?

因为我每天早上都会重新启动该过程,所以 TimedRotatingFileHandler 将无法工作。 该项目较大,因此我有兴趣保留登录日志配置文件所需的代码。

I have a process that I run every day. It uses Python logging. How would I configure the python logging module to write to a file containing the current date in the file name?

Because I restart the process every morning the TimedRotatingFileHandler won't work. The project is larger, so I would be interested in keeping the code required for logging into a logging configuration file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤独难免 2024-08-05 17:36:07

您可以使用 TimedRotatingFileHandler。 例如:

import logging
import logging.handlers

LOG_FILENAME = '/tmp/log'

# Set up a specific logger with our desired output level
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when='D')
log.addHandler(handler)

但这可能只有在您的程序运行超过一天的情况下才有效。 如果您的脚本每天在 cron 作业中启动,您最好手动格式化传递给日志处理程序的文件名以包含时间戳。

You can use the TimedRotatingFileHandler. For example:

import logging
import logging.handlers

LOG_FILENAME = '/tmp/log'

# Set up a specific logger with our desired output level
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when='D')
log.addHandler(handler)

But this will probably only work if your program runs for more than one day. If your script starts daily in a cron job you're better off manually formatting the filename which you pass to your log handler to include a timestamp.

溇涏 2024-08-05 17:36:07

您可能对 TimedRotatingFileHandler 感兴趣,请参阅 http://docs.python。 org/library/logging.html#logging.handlers.TimedRotatingFileHandler

You may be interested in the TimedRotatingFileHandler see http://docs.python.org/library/logging.html#logging.handlers.TimedRotatingFileHandler

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文