python - 如何拥有所有日志?
问题描述
我尝试对日志进行基本配置。我知道我在代码中有一个 KeyError 和一个 KeyError 但它没有在日志文件中显示这个错误。
(我使用 Sanic 和 Uvicorn)
api.py
uvicorn.run(
app, # Sanic app
host=config['sanic']['host'],
port=config['sanic']['port'],
log_level=logging.DEBUG,
log_config=logging.basicConfig(
filename='logs/logtest.log',
filemode='w',
level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
)
)
日志测试日志
2020-05-18 13:16:05,449 DEBUG Using selector: SelectSelector
2020-05-18 13:16:05,456 INFO Started server process [1736]
2020-05-18 13:16:05,456 INFO Waiting for application startup.
2020-05-18 13:16:05,457 INFO Application startup complete.
2020-05-18 13:16:05,457 INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
2020-05-18 13:16:08,939 INFO 127.0.0.1:65153 - "GET /index HTTP/1.1" 200
我想在日志文件中看到:
2020-05-18 13:16:08,939 INFO Traceback (most recent call last): File "<input>", line 1, in <module> KeyError: 'test'
抱歉,我不知道这是否可以理解,但是...感谢所有可以帮助我的人!
编辑:
def get_result() -> dict:
my_dict = {}
my_dict['test'] = "I know it's an ERROR but why it doesn't show in log !!"
return my_dict
@app.route('/index', methods=['GET'])
def index(request):
return get_result()
解决方案
uvicorn 的日志配置仅用于uvicorn 本身的日志。
要记录您的应用程序,您需要为您的应用程序单独配置日志记录。
阅读python 日志以了解如何做到这一点。配置日志记录后,您可以记录您的异常。
import logging
logger = logging.getLogger(__name__)
def get_result() -> dict:
try:
my_dict = {}
my_dict['test'] = "I know it's an ERROR but why it doesn't show in log !!"
return my_dict
except Exception:
logger.exception("Oops! Error occurred")
推荐阅读
- python - 用一年的 1/10 重采样 df,而不是每天、每月等
- c# - 如何搜索来自另一个页面模型的串联名称列表?
- time-complexity - 特定方法的大 O 表示法
- javascript - 将数据从 nodejs/express 传递到前端 js
- python - 使用 python pandas 删除 2 个不同文件中的重复行
- jquery - neo4j:jQuery 没有在 apoc.load.html 上返回预期结果
- datatable - 数据表 - 根据单元格值禁用表格内的按钮
- python - Python youtube-dl 可以得到合并文件的扩展名吗?
- c# - 如何在 CUA 环境中通过 BAPI 重置密码?
- c - 函数表 C 语法