我正在尝试使用logging.config.fileConfig
从.ini
文件初始化记录器。但是,当我致电fileConfig('logging_config.ini')
时收到错误消息:
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
代码:
import logging
from logging.config import fileConfig
fileConfig('logging_config.ini')
logger = logging.getLogger()
logger.debug('often makes a very good meal of %s', 'visiting tourists')
logger_config.ini:
[loggers]
keys=tcp_server
[handlers]
keys=stream_handler,file_handler
[formatters]
keys=formatter
[logger_root]
level=DEBUG
handlers=stream_handler
[handler_stream_handler]
class=StreamHandler
level=DEBUG
formatter=formatter
args=(sys.stderr,)
[handler_file_handler]
class=FileHandler
filename="tcp_server.log"
level=DEBUG
formatter=formatter
args=(sys.stderr,)
[formatter_formatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
完整的错误消息:
Traceback (most recent call last):
fileConfig('logging_config.ini')
File "C:\Program Files (x86)\Anaconda3\lib\logging\config.py", line 84, in fileConfig
handlers = _install_handlers(cp, formatters)
File "C:\Program Files (x86)\Anaconda3\lib\logging\config.py", line 148, in _install_handlers
h = klass(*args)
File "C:\Program Files (x86)\Anaconda3\lib\logging\__init__.py", line 1012, in __init__
filename = os.fspath(filename)
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
答案 0 :(得分:1)
当有人回答(但立即删除)时,您的.ini
文件是错误的。特别是当args=(sys.stderr,)
需要包含日志文件名称的字符串时,sys.stderr
会将FileHandler
作为FileHandler
的(单个)参数传递。 the documentation for using fileConfig
中对此进行了描述。请访问the top of the same page来找到教程和食谱的链接,因为fileConfig
通常是不安全的,并且不适合许多用例。
请注意,修复args
只会给您带来另一个错误,因为keys
部分中的[loggers]
设置是错误的:它必须至少列出一个root
键。它还应列出您可能使用的所有其他键,例如使用tcp_server.log
-文件FileHandler
实例的内容。然后,您可以通过logging.getLogger
使用具有处理程序限定名称的实例来使用。
结合所有三个修复程序(但同样不要这样做):
diff --git a/logging_config.ini b/logging_config.ini
index 8614b9f..ee1a66b 100644
--- a/logging_config.ini
+++ b/logging_config.ini
@@ -1,5 +1,5 @@
[loggers]
-keys=tcp_server
+keys=root,tcp_server
[handlers]
keys=stream_handler,file_handler
@@ -11,6 +11,12 @@ keys=formatter
level=DEBUG
handlers=stream_handler
+[logger_tcp_server]
+level=DEBUG
+handlers=file_handler
+propagate=0
+qualname=whatever
+
[handler_stream_handler]
class=StreamHandler
level=DEBUG
@@ -19,10 +25,9 @@ args=(sys.stderr,)
[handler_file_handler]
class=FileHandler
-filename="tcp_server.log"
level=DEBUG
formatter=formatter
-args=(sys.stderr,)
+args=("tcp_server.log",)
[formatter_formatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
diff --git a/tlog.py b/tlog.py
index 12a645a..bc3f07e 100644
--- a/tlog.py
+++ b/tlog.py
@@ -4,3 +4,5 @@ from logging.config import fileConfig
fileConfig('logging_config.ini')
logger = logging.getLogger()
logger.debug('often makes a very good meal of %s', 'visiting tourists')
+logger = logging.getLogger('whatever')
+logger.debug('tcp thing')