Pythonでログを出力する際にloggingを使っている方は多いと思います。loggingを使えば、単にログを書き出すだけではなくINFO
やDEBUG
、WARNING
、ERROR
、CRITICAL
といった「重要度のレベル」を添えてログを出力することができます。
また、どの程度のレベルまでを出力するかを指定することもできます。
たとえばERROR
よりも深刻なログだけを表示すると指定した場合、ERROR
とCRITICAL
のログだけが出力されます。
このように、非常に便利なloggingですが、デフォルトでは上述の5つのレベルしかありません。
ここでは、SUCCESS
という新たなログレベルを追加してみようと思います。WARNING
とINFO
の間のレベルとします。
import logging from logging import Formatter, getLogger, StreamHandler, FileHandler, DEBUG import sys import traceback formatter = Formatter('%(asctime)s - %(levelname)s - %(message)s') handler = StreamHandler(sys.stdout) handler.setLevel(DEBUG) handler.setFormatter(formatter) logger = getLogger(__name__) logger.addHandler(handler) logger.setLevel(DEBUG) # SUCCESSを追加 logging.SUCCESS = 25 # WARNINGとINFOの間 logging.addLevelName(logging.SUCCESS, 'SUCCESS') setattr(logger, 'success', lambda message, *args: logger._log(logging.SUCCESS, message, args)) # テストしてみます。 logger.debug('this is debug message') logger.info('this is info message') logger.success('this is success message') logger.warning('this is warning message') logger.error('this is error message') logger.critical('this is critical message') for i in range(10): try: a = 10/i if i == 5: i + 'hello world' logger.success('結果: {}'.format(a)) except Exception as e: logger.error(traceback.format_exc())
上記のコードの実行結果は以下のようになります。
$ python logging_test.py 2019-05-04 08:43:07,513 - DEBUG - this is debug message 2019-05-04 08:43:07,514 - INFO - this is info message 2019-05-04 08:43:07,514 - SUCCESS - this is success message 2019-05-04 08:43:07,514 - WARNING - this is warning message 2019-05-04 08:43:07,514 - ERROR - this is error message 2019-05-04 08:43:07,514 - CRITICAL - this is critical message 2019-05-04 08:43:07,514 - ERROR - Traceback (most recent call last): File "logging_test.py", line 27, in <module> a = 10/i ZeroDivisionError: division by zero 2019-05-04 08:43:07,514 - SUCCESS - 結果: 10.0 2019-05-04 08:43:07,515 - SUCCESS - 結果: 5.0 2019-05-04 08:43:07,515 - SUCCESS - 結果: 3.3333333333333335 2019-05-04 08:43:07,515 - SUCCESS - 結果: 2.5 2019-05-04 08:43:07,515 - ERROR - Traceback (most recent call last): File "logging_test.py", line 29, in <module> i + 'hello world' TypeError: unsupported operand type(s) for +: 'int' and 'str' 2019-05-04 08:43:07,515 - SUCCESS - 結果: 1.6666666666666667 2019-05-04 08:43:07,515 - SUCCESS - 結果: 1.4285714285714286 2019-05-04 08:43:07,515 - SUCCESS - 結果: 1.25 2019-05-04 08:43:07,515 - SUCCESS - 結果: 1.1111111111111112
うまくSUCCESSが表示されていることがわかります。 以上、今回はloggingにSUCCESSレベルを追加してみました。良い記事だと思っていただいた方は、SNSでのシェア、ブログからのリンク、「読者になる」ボタンのクリック、「★」ボタンのクリック、よろしくお願いします!