您正在尝试重制很差的东西,而Python标准库却做得很好。请检查日志记录模块。
使用此模块,您可以按照简单,标准和可扩展的方式完全执行所需的操作。您可以按照以下步骤进行操作(此示例是日志记录手册的复制/粘贴):
假设您要使用不同的消息格式和在不同的情况下登录控制台和文件。假设您要记录DEBUG或更高级别的消息到文件,而INFO或更高级别的消息记录到控制台。我们还假设该文件应包含时间戳,但控制台消息不应包含时间戳。这是实现此目的的方法:
import logging# set up logging to file - see previous section for more detailslogging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename='/temp/myapp.log', filemode='w')# define a Handler which writes INFO messages or higher to the sys.stderrconsole = logging.StreamHandler()console.setLevel(logging.INFO)# set a format which is simpler for console useformatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')# tell the handler to use this formatconsole.setFormatter(formatter)# add the handler to the root loggerlogging.getLogger().addHandler(console)# Now, we can log to the root logger, or any other logger. First the root...logging.info('Jackdaws love my big sphinx of quartz.')# Now, define a couple of other loggers which might represent areas in your# application:logger1 = logging.getLogger('myapp.area1')logger2 = logging.getLogger('myapp.area2')logger1.debug('Quick zephyrs blow, vexing daft Jim.')logger1.info('How quickly daft jumping zebras vex.')logger2.warning('Jail zesty vixen who grabbed pay from quack.')logger2.error('The five boxing wizards jump quickly.')运行此命令时,在控制台上,您将看到
root : INFO Jackdaws love my big sphinx of quartz.myapp.area1 : INFO How quickly daft jumping zebras vex.myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.myapp.area2 : ERROR The five boxing wizards jump quickly.
在文件中,您将看到类似
10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
如您所见,DEBUG消息仅显示在文件中。其他消息发送到两个目的地。
本示例使用控制台和文件处理程序,但是您可以使用任意数量和所选处理程序的组合。



