2

Say I have a While loop that runs forever(it does system monitoring).

It has three conditions,

While True:

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

The first, I don't want anything for. The second, I'd like to add a warning to a logfile. For the third, the same - except it's an error.

Since these are in a while loop, can I still just add a logger to something2 and something3? Do I start out with the below?

import logging logger = logging.getLogger()

But how do I add warning and error to each respective if statement so it writes to the same logfile?

cbll
  • 6,499
  • 26
  • 74
  • 117
  • 1
    Maybe this helps you [Follow me](http://stackoverflow.com/questions/11232230/logging-to-two-files-with-different-settings) – DomeTune Jan 20 '17 at 13:03

2 Answers2

7

try doing it like this

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')
Chandan Rai
  • 9,879
  • 2
  • 20
  • 28
  • 1
    The information of warning or error (file, line, and error / warning itself) are not printed. It is important to use in these cases : logging.captureWarnings(True) ... to capture the warning. – Clément v Sep 20 '21 at 12:55
3

Use logging module:

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)
...

Also you can write logging.warning and logging.info, as @crai noted.

Dmitry
  • 2,026
  • 1
  • 18
  • 22