Skip to content
Advertisement

log file error in in Raspberry with Python

I am use Python3 in my Raspberry Pi, and I have a code that someone has shared with me, the following line is shown to record the log file:

logging.basicConfig(filename='/Desktop/var/log/morning/RER-execution-logs.txt',format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO)

but when I tray to run the code using Python on my Raspberry I get the following error:

Traceback (most recent call last):
File "test.py", line 709, in <module>
main(sys.argv)
File "test.py", line 641, in main
logging.basicConfig(filename='/var/log/morning/RER-execution-logs.txt',format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO)
File "/usr/lib/python3.7/logging/__init__.py", line 1900, in basicConfig
h = FileHandler(filename, mode)
File "/usr/lib/python3.7/logging/__init__.py", line 1092, in __init__
StreamHandler.__init__(self, self._open())
File "/usr/lib/python3.7/logging/__init__.py", line 1121, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
FileNotFoundError: [Errno 2] No such file or directory: '/var/log/morning/RER-execution-logs.txt'

I have also created the directory and the file manually but I get this other error:

Traceback (most recent call last):
File "test.py", line 709, in <module>
main(sys.argv)
File "test.py", line 641, in main
logging.basicConfig(filename='/var/log/morning/RER-execution-logs.txt',format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO)
File "/usr/lib/python3.7/logging/__init__.py", line 1900, in basicConfig
h = FileHandler(filename, mode)
File "/usr/lib/python3.7/logging/__init__.py", line 1092, in __init__
StreamHandler.__init__(self, self._open())
File "/usr/lib/python3.7/logging/__init__.py", line 1121, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
PermissionError: [Errno 13] Permission denied: '/var/log/morning/RER-execution-logs.txt

what am I doing wrong

Advertisement

Answer

It is simply because the file that you are trying to log on does not actually exist. You could either create it manually, or use the below version of your Python script which will create it for you, if it does not exist already:

import logging, os

logPath = '/Desktop/var/log/morning/RER-execution-logs.txt'

if not os.path.exists(logPath):
    open(logPath, 'w+').close()

logging.basicConfig(filename=logPath,format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO)

However make sure that the path to that log file is actually correct. To be extra sure, use the absolute path. You are looking to something like:

/home/pi/Destkop/...

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement