python logging module no output while running in crontab

时间:2015-12-10 01:41:52

标签: python linux shell crontab centos6

I hava executable a.py file worked fine when running in CLI. But after I wrote a a.sh script /root/a.py >> /root/a.log and start a crontab * * * * * /bin/sh /root/a.sh, it worked fine except no outputting in the log file.
The logging part of a.py was configured as follows:

DATE_FORMAT = '%a, %d %b %Y %H:%M:%S'
LOG_FILE = 'log'
RESULT_LOG_FILE = 'result.log'
LOG_FORMAT = '[%(asctime)s] [%(filename)s:%(lineno)d] [%(levelname)s] [%(threadName)s] [%(process)d] %(message)s'
logging.basicConfig(format=LOG_FORMAT, datefmt=DATE_FORMAT, level=logging.INFO, filename=LOG_FILE)  
logging.error('ERROR')  

I have tried to add /usr/local/bin/python in front of /root/a.py in a.sh but it did not work. I have no idea why this happened.

1 个答案:

答案 0 :(得分:6)

The command /root/a.py >> /root/a.log does output redirection into the file /root/a.log. The >> = append, whereas > would overwrite.

Your script is logging to result.log, not a.log. And unless you have a print statement, nothing is going to go into a.log.

In your logging.basicConfig, log events are not output to console, only to the log file, so there is no "output" to re-direct to a.log.

(Add a print 'hello console' in your script, you should see that in a.log.)

Edit from comments:

result.log may not be where you think. Since its path is determined by where it's executed from, not where the script is. Change RESULT_LOG_FILE = 'result.log' to RESULT_LOG_FILE = '/root/result.log'