Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing logs using crontab

I am using crontab to autostart the program, using the following command in cronatb

@reboot sudo python /home/Desktop/Appllication.py

Is it possible to write all the logs (errors and other stuff) by appending something to the above command, so that cron writes all errors/ any related events to a log ?

UPDATE: The code prints values in the python idle terminal when run individually using the print command. How do I make this data which is printed on the terminal to be written to the log file. for ex, if my code is like print "food morning" , how do I get this to be written into the log file instead of printing on terminal.

TEST CODE:

import time
while(1):
    print "testing"
    time.sleep(5)
like image 241
bobdxcool Avatar asked Dec 27 '14 22:12

bobdxcool


2 Answers

You are actually including a sudo in there. Sudo requires a password, you would have to add a configuration item in sudoers to run that script passwordless. Your other option is to add it to the root cron. Use @Haleemur's redirection command to redirect the output to the logs. I would actually suggest using the following as well just in case it fails and outputs to STDERR

@reboot python /home/Desktop/Application.py >> /home/Desktop/log_file 2>&1

UPDATE:

try running the following command from the terminal

python /home/Desktop/Application.py >> /home/Desktop/log_file 2>&1

if it works in the command line, there is no reason it shouldn't work in cron.

like image 191
Digisec Avatar answered Oct 07 '22 12:10

Digisec


if /home/Desktop/Application.py prints the error log to STDOUT, you can simply redirect the output of the script like this

python /home/Desktop/Application.py >> /home/my_application_log.txt

Expanding the answer with a couple of useful links.

Redirect all output to file is a really good SO thread. You can try the code snippet there using your test code as the output generator.

Also, python comes with an excellent logging module. If you want to incorporate a robust logging system, I highly recommend looking into it: python logging

like image 21
Haleemur Ali Avatar answered Oct 07 '22 12:10

Haleemur Ali