Reputation: 755
Ubuntu server 16.04.5 LTS
I have a python script which creates log files using the following code:
today = datetime.today()
datem = datetime(today.year, today.month, today.day)
logger = logging.getLogger('processImport')
hdlr = logging.FileHandler('{0}myLog_{1}-{2}-{3}.log'.format(myLogFileLocation, datem.year, datem.month, datem.day))
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
saving a log entry with:
logger.info(logMessage)
I then have a cron job that deletes older log files after a certain period by executing a python file which uses os.remove(fullFilePath)
to delete the file.
However, I am getting a permissions error when this cron job executes.
OSError: [Errno 13] Permission denied: PathToTheFile\theLogFileName.log
When I check the permissions for the file they are set to:
-rw-r--r-- 1 www-data www-data etc etc
What do I need to do to enable the cron job to have permission to delete the log files please?
Thank you.
Upvotes: 10
Views: 23821
Reputation: 544
Maybe u need to change your process umask
>>> import os
>>> from pathlib import Path
>>> Path('default').touch()
>>> os.umask(0o000)
2
>>> Path('changed').touch()
>>> exit()
$ ls -lah
drwxrwxrwt 1 root root 4.0K Oct 13 22:07 .
drwxr-xr-x 1 root root 4.0K Oct 13 21:48 ..
-rw-rw-rw- 1 urs urs 0 Oct 13 22:07 changed
-rw-rw-r-- 1 urs urs 0 Oct 13 22:07 default
Read also: Does python logging.handlers.RotatingFileHandler allow creation of a group writable log file?
Upvotes: 1
Reputation: 1166
There seems to be a write issue permission with the folder. Changing the permission should help.
Try this:
log_dir = '/abs/path/of/directory'
os.chmod(log_dir, 0777) # for Python2
os.chmod(log_dir, 0o777) # for Python3
Let me know how it goes.
Note that Python3 requires prefixing octal numbers with 0o
now instead of just 0
. See here: Invalid Token when using Octal numbers. Otherwise you'll get this error:
SyntaxError: invalid token
Upvotes: 10