1つのデコレータで、history.logとerror.logを分けて判定して出力できる?
はい、1つのデコレータで、history.log と error.log を分けて判定して出力することができます。以下はその例です。
python
import functools import logging def log_history_and_errors(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: result = func(*args, **kwargs) logging.info(f"Function {func.__name__} was executed successfully.") return result except Exception as e: logging.error(f"Error in function {func.__name__}: {str(e)}", exc_info=True) raise # エラーを再度発生させて呼び出し元に伝搬させます return wrapper logging.basicConfig(level=logging.INFO) # ヒストリーログ用の設定 history_logger = logging.getLogger('history') history_logger.setLevel(logging.INFO) history_handler = logging.FileHandler('history.log') history_formatter = logging.Formatter('%(asctime)s - %(message)s') history_handler.setFormatter(history_formatter) history_logger.addHandler(history_handler) # エラーログ用の設定 error_logger = logging.getLogger('error') error_logger.setLevel(logging.ERROR) error_handler = logging.FileHandler('error.log') error_formatter = logging.Formatter('%(asctime)s - %(message)s') error_handler.setFormatter(error_formatter) error_logger.addHandler(error_handler) @log_history_and_errors def example_function(x, y): if y == 0: raise ValueError("Cannot divide by zero.") return x / y # ログ出力 example_function(10, 2) example_function(10, 0)
この例では、1つのデコレータ log_history_and_errors を使用して、関数の実行履歴を history.log に、エラーを error.log に出力しています。デコレータ内で、それぞれのログに対する設定を行っています。

ディスカッション
コメント一覧
まだ、コメントがありません