Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python logging module no output while running in crontab

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.

like image 713
J.Wang Avatar asked Apr 07 '26 23:04

J.Wang


1 Answers

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'

like image 134
aneroid Avatar answered Apr 09 '26 12:04

aneroid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!