3

Python のログ モジュールでエラーをログに記録しています。次のように、クラス内にロガー オブジェクトを作成しました。

self.my_logger = logging.getLogger('my_logger')
self.my_logger.setLevel(logging.ERROR)

コードの後半でエラーをログに記録しようとすると、次のようになります。

self.my_logger.error("My error")

次に、エラーが発生します。

AttributeError: FileHandler instance has no attribute 'filters'

より詳細なエラー ログは次のとおりです。

  File "/lib/python2.6/logging/__init__.py", line 1047, in error
    self._log(ERROR, msg, args, **kwargs)
  File "/lib/python2.6/logging/__init__.py", line 1129, in _log
    self.handle(record)
  File "/lib/python2.6/logging/__init__.py", line 1139, in handle
    self.callHandlers(record)
  File "/lib/python2.6/logging/__init__.py", line 1176, in callHandlers
    hdlr.handle(record)
  File "/lib/python2.6/logging/__init__.py", line 658, in handle
    rv = self.filter(record)
  File "/lib/python2.6/logging/__init__.py", line 558, in filter
    for f in self.filters:
AttributeError: FileHandler instance has no attribute 'filters'

これの上流で、ファイルハンドラーを設定する方法は次のとおりです。

 if self.log_dir != None:
    self.log_filename = os.path.join(self.log_dir, 'run.%s' \
                                     %(time.strftime("%m-%d-%y_%H:%M:%S")))

 ch_file = logging.FileHandler(self.log_filename,
                                  delay=True)
 ch_file.setLevel(logging.ERROR)
 ch_file.setFormatter(formatter)
 self.my_logger.addHandler(ch_file)

 ch_stream = logging.StreamHandler()
 ch_stream.setLevel(logging.INFO)

 # add formatter to ch
 ch_stream.setFormatter(formatter)

 # add ch to logger
 self.my_logger.addHandler(ch_stream)
 self.my_logger.info("Ready.")

ここで何が起こっているのか分かりますか?ありがとう。

4

1 に答える 1

8

名前が標準のものと衝突するモジュールを定義していないことを確認してください。以下のわずかに変更されたスクリプトは、私のシステムでエラーなく実行されます。自分で試してみて、うまくいく場合は、同じ名前のクラスを再定義していないことを再確認してください。

import logging
import os
import time

class SomeClass:
    def __init__(self):
        self.log_dir = os.getcwd()
        formatter = logging.Formatter('%(asctime)s %(message)s')
        self.my_logger = logging.getLogger('my_logger')
        self.my_logger.setLevel(logging.INFO)

        if self.log_dir != None:
            self.log_filename = os.path.join(self.log_dir, 'run.log')

        ch_file = logging.FileHandler(self.log_filename, 'w')
        ch_file.setLevel(logging.ERROR)
        ch_file.setFormatter(formatter)
        self.my_logger.addHandler(ch_file)

        ch_stream = logging.StreamHandler()
        ch_stream.setLevel(logging.INFO)

        # add formatter to ch
        ch_stream.setFormatter(formatter)

        # add ch to logger
        self.my_logger.addHandler(ch_stream)
        self.my_logger.info("Ready.")

        self.my_logger.error("My error")


def main():
    SomeClass()

if __name__ == '__main__':
    main()

ところで、あなたがこれについて質問していないことは知っていますが、ロガーをインスタンス変数として保存することは推奨されていません。とにかくシングルトンであるため、意味がありません。ほとんどのユーザーにとって通常のアプローチは、単一の

logger = logging.getLogger(__name__)

モジュールレベルで、それをモジュール全体で使用します。より細かくする必要がある場合は__name__、プレフィックスとして使用してロガーの子ロガーを作成します (例: '%s.detail' % __name__)

于 2010-12-04T01:37:52.937 に答える