所以我正在使用我发现并稍微调整的异常日志记录模块。但我似乎无法弄清楚为什么它不会创建一个文件并写入它。
这是我的模块:
"""Exception logging"""
import sys
import traceback
import logging
logger = logging
def setup_logging_to_file():
logger = logging.basicConfig( filename='error_log.txt',
filemode='w',
level=logging.DEBUG,
format= '%(asctime)s - %(levelname)s - %(message)s',
)
def log_exception(e):
logger.error(
"Function {function_name} raised {exception_class} ({exception_docstring}): {exception_message}".format(
function_name = extract_function_name(), #this is optional
exception_class = e.__class__,
exception_docstring = e.__doc__,
exception_message = e.message))
def extract_function_name():
tb = sys.exc_info()[-1]
stk = traceback.extract_tb(tb, 1)
fname = stk[0][3]
return fname
我在启动时运行setup_logging_to_file()
然后每当我遇到异常时我都会调用log_exception
并将异常传递给它,但它甚至不会创建error_log.txt
文件
from app.exception_logging import log_exception, setup_logging_to_file
def myFunc():
try:
....
except Exception as ex:
log_exception(ex)
答案 0 :(得分:1)
我遇到了同样的问题。最后我决定这样做:
import logging.config
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("log_file.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
然后在代码中,您可以按如下方式使用记录器:
logger.info('message')
logger.error('message')
答案 1 :(得分:0)
正如评论中所建议的那样 - 您可以直接访问日志记录。
工作示例,名为logtest.py的文件:
"""Exception logging"""
import sys
import traceback
import logging
logging.basicConfig( filename='/tmp/error_log.txt',
filemode='w',
level=logging.DEBUG,
format= '%(asctime)s - %(levelname)s - %(message)s',
)
def log_exception(e):
logging.error(
"Function {function_name} raised {exception_class} ({exception_docstring}): {exception_message}".format(
function_name = extract_function_name(), #this is optional
exception_class = e.__class__,
exception_docstring = e.__doc__,
exception_message = e.message))
def extract_function_name():
tb = sys.exc_info()[-1]
stk = traceback.extract_tb(tb, 1)
fname = stk[0][3]
return fname
目标文件:
from logtest import log_exception
try:
open("somthingnotthere",'r')
except Exception as ex:
log_exception(ex)