Pythonロギングモジュール

関連知識の記録

ログレベル 使用するシーン
デバッグ 詳細情報。通常、問題のデバッグ時にのみ使用されます。
情報 物事が期待どおりに機能していることを証明する
警告 予期しない時間のプロンプト、または将来発生する可能性のある問題のプロンプト
エラー より深刻な問題のため、ソフトウェアは一部の機能を実行できなくなりました
クリティカル 重大なエラーは、ソフトウェアが実行できなくなったことを示します

注:
重大度レベル:CRITICAL> ERROR> WARNING> INFO> DEBUG
デフォルトレベル:WARNING
出力ログレベルを設定します。ログレベルがWARNINGの場合、ログはWARNING以上のログコンテンツのみを出力でき、重大度レベルはWARING未満です。は出力されない
デフォルトの世代です
ルートロガーのレベルはlogging.WARNINGであり、このレベルより下のレベルは出力されません。

Formatterオブジェクトは、ログ情報の最終的なルール、構造、および内容を設定します

パラメータ 出力コンテンツ
%(名前)s ロガーの名前
%(levelno)s デジタルログレベル
%(メッセージ)s ユーザー出力情報
%(レベル名)s テキスト形式のログレベル
%(パス名)s ログ出力関数を呼び出すモジュールのフルパス名。そうでない場合もあります。
%(ファイル名)s ログ出力関数を呼び出すモジュールのファイル名
%(モジュール)s ログ出力関数を呼び出すモジュールの名前
%(lineno)d ログ出力関数を呼び出すステートメントが配置されているコード行
%(asctime)s 文字列としての現在の時刻。デフォルトの形式は「2003-07-0816:49:45,896」です。カンマからミリ秒後
%(スレッド)d スレッドID、できない場合があります
%(threadName)s スレッド名。そうでないかもしれない

コンソールへのロギング

import logging
logging.debug('it is debug')
logging.info('it is info')
logging.warning('it is waring')
logging.error('it is error')
logging.critical('it is critical')
输出只有:
WARNING:root:it is waring
ERROR:root:it is error
CRITICAL:root:it is critical
注释: 默认生成的root logger的level是logging.WARNING,低于该级别的就不输出了

出力をファイルに記録する

import logging
#创建一个logger
logger = logging.getLogger()
#设置log等级开关
logger.setLevel(logging.INFO)
logfile = 'recorder.log'
fh = logging.FileHandler(logfile, mode='w', encoding='utf-8')
#设置输出格式
fh.setLevel(logging.DEBUG)
#设置格式
formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
fh.setFormatter(formatter)
#将logger添加到hander里面
logger.addHandler(fh)
logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is a logger critical message')

シンプルなログデコレータ

import logging
import json

def create_log():
    logger = logging.getLogger()
    # 设置log等级开关
    logger.setLevel(logging.INFO)
    logfile = 'warrp.log'
    fh = logging.FileHandler(logfile, mode='w', encoding='utf-8')
    # 设置输出格式
    fh.setLevel(logging.DEBUG)
    # 设置格式
    formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
    fh.setFormatter(formatter)
    # 将logger添加到hander里面
    logger.addHandler(fh)
    return logger


def write_log(func):
    def wrapper():
        result = func()
        logger = create_log()
        logger.info(json.dumps(result))
        return result
    return wrapper

@write_log
def func():
    return {
    
    'name': 'hh', 'age': 20}

if __name__ == '__main__':
	func()

おすすめ

転載: blog.csdn.net/xxy_yang/article/details/107913769