When trying to write to a log file, i get the error OSError: [Errno 22] Invalid argument
The code i am using is as follows:
import datetime
import logging
logger = logging.getLogger('k')
hdlr = logging.FileHandler('Path to the log file/Logs/log'+str(datetime.datetime.now())+'.log')
formatter = logging.Formatter('At %(asctime)s, the program returned %(message)s at level %(levelname)s
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
logger.info('Hello')
Does the 'Path to the log file' directory exists in your working directory?
You have a directory called 'Path to the log file' and its subdir 'Logs'?
Post the full error traceback in error tags, please.
Error:
Traceback (most recent call last):
File "C:\Users\Richard\Desktop\Atom\K\K.py", line 20, in <module>
hdlr = logging.FileHandler('/Users/Richard/Desktop/Atom/K/Logs/log'+str(datetime.datetime.now())+'.log')
File "C:\Users\Richard\AppData\Local\Programs\Python\Python36-32\lib\logging\__init__.py", line 1025, in __init__
StreamHandler.__init__(self, self._open())
File "C:\Users\Richard\AppData\Local\Programs\Python\Python36-32\lib\logging\__init__.py", line 1054, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
OSError: [Errno 22] Invalid argument: 'C:\\Users\\Richard\\Desktop\\Atom\\K\\Logs\\log2018-06-03 09:53:07.712997.log'
I presume that you are following some book or tutorial.
On line 4 in your code, instead of 'Path to the log file' put your path 'C:/Users/Richard/Desktop/Atom/K'.
hdlr = logging.FileHandler(''C:/Users/Richard/Desktop/Atom/K/Logs/log'+str(datetime.datetime.now())+'.log')
(Jun-03-2018, 02:21 PM)wavic Wrote: [ -> ]I presume that you are following some book or tutorial.
On line 4 in your code, instead of 'Path to the log file' put your path 'C:/Users/Richard/Desktop/Atom/K'.
hdlr = logging.FileHandler(''C:/Users/Richard/Desktop/Atom/K/Logs/log'+str(datetime.datetime.now())+'.log')
That is what is there. I still get the error.
Yea I left one quote when I pasted it. The path to the file is not 'Path to the log file/Logs' but 'C:/Users/Richard/Desktop/Atom/K/Logs'
hdlr = logging.FileHandler('C:/Users/Richard/Desktop/Atom/K/Logs/log'+str(datetime.datetime.now())+'.log')
If you give you an error post it.
(Jun-03-2018, 02:30 PM)wavic Wrote: [ -> ]Yea I left one quote when I pasted it. The path to the file is not 'Path to the log file/Logs' but 'C:/Users/Richard/Desktop/Atom/K/Logs'
hdlr = logging.FileHandler('C:/Users/Richard/Desktop/Atom/K/Logs/log'+str(datetime.datetime.now())+'.log')
If you give you an error post it.
Perhaps you don't understand. This was there the entire time. I just didn't say the full path.
the colon is not allowed in file name. Use something like
hdlr = logging.FileHandler('Path to the log file/Logs/log{}.log'.format(datetime.datetime.strftime(datetime.datetime.now(), '%Y%m%d%H%M%S_%f'))