2017-01-20 4 views
0

Whileループが永久に実行されているとします(システムの監視を行います)。Python 3:ログファイルに警告とエラーを記録する方法は?

それは三つの条件があり、

While True: 

    if something1 
     Everything is OK! 
    if something2 
     Warning 
    if something3 
     Error 

最初、私はのために何もしたくありません。次に、ログファイルに警告を追加したいと思います。 3番目の場合は同じですが、それはエラーです。

これはwhileループなので、まだsomething2とsomething3にロガーを追加できますか?私は以下から始めますか?

import logging logger = logging.getLogger()

しかし、どのように文の場合、それは同じログファイルに書き込みますので、私はそれぞれに警告やエラーを追加するには? @craiが指摘したよう

import logging 
logging.basicConfig(filename='logfile.log', level=logging.DEBUG, 
        format='%(asctime)s %(levelname)s %(name)s %(message)s') 
logger=logging.getLogger(__name__) 
...  

try: 
    1/0 
except ZeroDivisionError as err: 
    logger.error(err) 
... 

また、あなたは、logging.warninglogging.infoを書き込むことができます。

+1

これは多分あなたに役立ちます[私に従ってください](http://stackoverflow.com/questions/11232230/logging-to-two-files-with-different-settings) – DomeTune

答えて

2

この

import logging 
logging.basicConfig(filename='example.log',level=logging.DEBUG) 
logging.debug('This message should go to the log file') 
logging.info('So should this') 
logging.warning('And this, too') 
1

使用loggingモジュールのようにそれをやってみてください。

関連する問題