ロギングモジュールのドキュメントを読みましたが、明らかなことを見逃しているかもしれませんが、取得したコードが意図したとおりに機能していないようです。Python2.6.4を使用しています。
私のプログラムはいくつかの異なるPythonファイルで構成されており、そこからログメッセージをテキストファイルと、場合によっては画面に送信します。これはよくあることだと思うので、どこかでこれを台無しにしています。
私のコードがその瞬間に行っていることは、テキストファイルに正しくログを記録することです。ただし、画面へのログ記録は複製されており、1つは指定されたフォーマットで、もう1つはフォーマットなしです。また、画面出力をオフにしても、テキストが1回印刷されるので、必要ありません。ファイルに記録するだけです。
とにかく、いくつかのコード:
#logger.py
import logging
from logging.handlers import RotatingFileHandler
import os
def setup_logging(logdir=None, scrnlog=True, txtlog=True, loglevel=logging.DEBUG):
logdir = os.path.abspath(logdir)
if not os.path.exists(logdir):
os.mkdir(logdir)
log = logging.getLogger('stumbler')
log.setLevel(loglevel)
log_formatter = logging.Formatter("%(asctime)s - %(levelname)s :: %(message)s")
if txtlog:
txt_handler = RotatingFileHandler(os.path.join(logdir, "Stumbler.log"), backupCount=5)
txt_handler.doRollover()
txt_handler.setFormatter(log_formatter)
log.addHandler(txt_handler)
log.info("Logger initialised.")
if scrnlog:
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)
log.addHandler(console_handler)
そこには何も珍しいことはありません。
#core.py
import logging
corelog = logging.getLogger('stumbler.core') # From what I understand of the docs, this should work :/
class Stumbler:
[...]
corelog.debug("Messages and rainbows...")
画面出力は、これがどのように複製されているかを示しています。
2010-01-08 22:57:07,587 - DEBUG :: SCANZIP: Checking zip contents, file: testscandir/testdir1/music.mp3
DEBUG:stumbler.core:SCANZIP: Checking zip contents, file: testscandir/testdir1/music.mp3
2010-01-08 22:57:07,587 - DEBUG :: SCANZIP: Checking zip contents, file: testscandir/testdir2/subdir/executable.exe
DEBUG:stumbler.core:SCANZIP: Checking zip contents, file: testscandir/testdir2/subdir/executable.exe
テキストファイルは正しくフォーマットされた出力を取得していますが、logger.pyで画面ログをオフにしても、正しくフォーマットされていない出力が表示されます。
私がドキュメントについて理解していることから、corelog.debug()を呼び出すと、corelogは「つまずき」ロガーの子であるため、そのフォーマットを使用してログを出力する必要があります。
そのような些細な問題についてのエッセイについてお詫びします。
TL; DR:複数のファイルからログを記録するにはどうすればよいですか?