在同一个文件中记录不同的 python 个文件

Logging different python files in the same file

我有一个名为 bar.py 的自定义模块,我将其导入到我的一些脚本中。它实际上是通过 pip install 从 pypi 索引导入的。 bar.py 模块看起来像这样(这实际上是我实际拥有的一个过于简单的例子,所以我可以在这里解决我的疑问。

import logging

def do_bar_logged():
    logging.INFO('START DOING SOMETHING')
    do_bar()
    logging.INFO('END DOING SOMETHING')

我在其中导入 bar 的 do_bar_logged 的脚本之一称为 foo.py。它看起来像这样。

import logging
from bar import do_bar_logged  # I need to install via pip bar before being able to import this, just like a regular module.

def main():
    logging.INFO('START CALLING DO_BAR')
    do_bar_logged()
    logging.INFO('END CALLING DO_BAR')

我的问题是:是否可以让两个日志记录指向同一个文件而不对任何内容进行硬编码?

您可以像这样使用 logging 模块

bar.py

import logging


def aux_print():
    logging.warning('This is my auxiliary script')

main.py

import logging
from bar import aux_print

logging.basicConfig(
    filename="log.txt",
    filemode='a',
    format='[%(asctime)s,%(msecs)d] [%(levelname)s]: %(message)s',
    datefmt='%H:%M:%S',
    level=logging.DEBUG
)


def main():
    logging.info('This is my main script')
    aux_print()


if __name__ == '__main__':
    main()

输出log.txt

[18:58:23,708] [INFO]: This is my main script
[18:58:23,708] [WARNING]: This is my auxiliary script

logging 模块可让您将对 print 的调用替换为对可以以各种方式配置为 运行 的特殊日志记录函数的调用。当您替换后端处理程序以记录您想要的位置时,顶端日志记录调用保持不变。

将多个脚本记录到一个目的地可能很棘手。您不能只写一个文件,因为日志往往会相互覆盖(锁定文件处理程序可以提供帮助)。最简单的事情之一是使用 SysLogHandler (linux/mac) 和 NTEventLogHandler (windows) 处理程序记录到常规系统日志。

或者您可以使用一些低级处理程序(HTTP、套接字、dgram、队列)来编写您自己的聚合日志的日志记录服务器。您甚至可以使用 SQL 或 NOSQL 处理程序来登录数据库。日志记录很重要,那里有很多第 3 方日志记录模块。值得一看,看看有没有对你有用的。