简体   繁体   中英

logging only stderr to a logfile using python logger

I have a logger set up, but I couldn't figure out how to log only if the command fails or generates stderr.

def RunAndLog(self, command, logf)
   p = subprocess.Popen(command, shell=False, 
           stdout=subprocess.PIPE, stderr=subprocess.PIPE)
   (stdout, stderr) = p.communicate()
   logger = logging.getLogger('check rel')
   logger.setLevel(logging.ERROR)
   filehand = logging.handlers.RotatingFileHandler(logFile, mode='a',maxBytes=0,
              backupCount=0, encoding=None, delay=0)
   filehand.setLevel(logging.ERROR)
   lformat = logging.Formatter('%(message)s')
   filehand.setFormatter(lformat)
   logger.addHandler(filehand)
   logger.info(stdout)
   logger.error(stderr)
   logger.removeHandler(filehand)

I am calling this for listing directories. Something like,

self.RunAndLog(["dir","%s",pathtodir], "test.log")

test.log contains messages for both cases, ie, when the directory doesn't exist and also when it does... Here is an example :

#case where dir doesn't exist
dir: /path/to/dir/dir1: No such file or directory

# case where it does
bin lib include src test python doc

How can I log messages to test.log only for the cases where the directory doesn't exist or only where the dir command fails with non-zero exit status ?

Thanks...

Your filehandler handler is catching all log messages. You set its level to ERROR, which makes it catch all messages from ERROR and up (including INFO), that's why every message you log is going into the file.

If you want more control, you'll have to add Filter objects too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM