Pythonでログをファイルに出力する

概要

Pythonでファイルにログを出力する場合は、loggingモジュールを使う。

コード

import logging

logger = logging.basicConfig(filename='logs/debug.log', level=logging.DEBUG)

def example():
    res = requests.get(HOGEHOGE, data=json.dumps(payload), headers=headers)
    res_json = res.json()
    logging.info(res_json)

    try:
        ~~~
    except Exception as e:
        logging.error(e.message)