首页 > 解决方案 > 如何拥有所有日志?

问题描述

我尝试对日志进行基本配置。我知道我在代码中有一个 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()

标签: pythonloggingsanicuvicorn

解决方案


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")

推荐阅读