使用PyInstaller打包的应用程序中日志记录异常:调用模块和函数设置为'logging'和'debug

1 投票
1 回答
1223 浏览
提问于 2025-04-18 10:21

我有一个用Python写的应用程序,它使用了一个叫做'logging'的模块,我用pyinstaller把它打包。

我使用了下面这个格式字符串:

%(asctime)s %(levelname)s [%(threadName)s:%(module)s.%(funcName)s()] %(message)s

如果我直接运行这个应用程序作为Python脚本,它工作得很好,'%(module)s.%(funcName)s'会被调用的模块和函数的实际值替换:

2014-06-19 18:46:10,373 DEBUG [MainThread:subcommands.exec_cmd()] Executing `service iptables stop` on server centos6root
2014-06-19 18:46:10,373 DEBUG [MainThread:ssh._connect()] Trying to connect to server centos6root
2014-06-19 18:46:10,945 DEBUG [MainThread:ssh._connect()] Established connection with root@192.168.122.57:22
2014-06-19 18:46:11,533 DEBUG [MainThread:subcommands.exec_cmd()] exitstatus = 0
2014-06-19 18:46:11,648 DEBUG [MainThread:ssh.cleanup()] Closed connection to server centos6root
2014-06-19 18:46:11,649 DEBUG [MainThread:hwswa2.main()] Application finished

但是,如果我用pyinstaller打包我的应用程序,它现在把'logging.debug'替换成了'%(module)s.%(funcName)s':

2014-06-19 19:04:05,577 DEBUG [MainThread:logging.debug()] Executing `echo hello` on server centos6root
2014-06-19 19:04:05,577 DEBUG [MainThread:logging.debug()] Trying to connect to server centos6root
2014-06-19 19:04:06,293 DEBUG [MainThread:logging.debug()] Established connection with root@192.168.122.57:22
2014-06-19 19:04:06,705 DEBUG [MainThread:logging.debug()] exitstatus = 0
2014-06-19 19:04:06,707 DEBUG [MainThread:logging.debug()] Closed connection to server centos6root
2014-06-19 19:04:06,707 DEBUG [MainThread:logging.debug()] Application finished

这可能是什么原因呢?我该怎么解决这个问题呢?

1 个回答

1

我之前直接使用 logging.info()logging.debug() 这些函数来记录日志。

后来我发现,给每个模块使用不同的日志记录器可以解决这个问题。

import logging
logger = logging.getLogger(__name__)

所以我开始用 logger.info()logger.debug() 这些来记录日志。

撰写回答