Allure Behaveでテストをする際に、
標準出力・標準エラー出力を検査結果に添付する方法は、
次のエントリでまとめました。

Allure Behaveで標準出力・標準エラー出力を検査結果に添付する
https://takemikami.com/2024/0605-allure-behave-stdout.html

このエントリでは、同様にしてログも添付できると便利だと思うので、
その手順をまとめておきます。

テストコードの作成

以下のように、ログを出力するテストコードを用意します。

sample.feature

Feature: sample feature

  Scenario: senario1
    When process1

steps/sample.py

from behave import *
import logging

logger = logging.getLogger()

@when("process1")
def step_impl(context):
  logger.debug('デバッグログ')
  logger.info('情報ログ')
  logger.warning('警告ログ')

ログ出力をレポートに出力する対応

標準出力・標準エラー出力の場合と同じように、
before_step, after_stepで、ログのハンドラーを追加・削除、
after_stepには、更にハンドラーのバッファを出力し、検査結果に添付します。

environment.py

import allure
import logging
import logging.handlers

def before_all(context):
    context.log_handler = logging.handlers.BufferingHandler(1000)
    context.log_handler.setFormatter(logging.Formatter(context.config.logging_format, context.config.logging_datefmt))
    context.log_handler.setLevel(context.config.logging_level)

def before_step(context, step):
    context.log_handler.flush()
    root_logger = logging.getLogger()
    root_logger.addHandler(context.log_handler)

def after_step(context, step):
    root_logger = logging.getLogger()
    root_logger.removeHandler(context.log_handler)
    logstr = '\n'.join(context.log_handler.formatter.format(r) for r in context.log_handler.buffer)
    if len(logstr) > 0:
      allure.attach(logstr, name="ログ出力", attachment_type=allure.attachment_type.TEXT)

ログレベルやフォーマットは、behaveの設定を使い回すので、
behaveの設定ファイルにそれぞれの設定値を追記しておきます。

.behaverc

[behave]
format=allure_behave.formatter:AllureFormatter
outfiles=allure-results

logging_format=[%(asctime)s][%(levelname)s](%(filename)s:%(lineno)s) %(message)s
logging_datefmt=%Y/%m/%d %H:%M:%S
logging_level=DEBUG

以上。