简体   繁体   中英

Python Logger Invalid Argument for FileHandler

Hi when I am writing the following code in python

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('ThingsSpeakRESTAPI.log')
fh.setLevel(logging.DEBUG)

The log file is created in the name ThingsSpeakRESTAPI.log

But If I do:

filename = datetime.datetime.now().isoformat()+"LOG.log"
print(filename)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler(filename)
fh.setLevel(logging.DEBUG)

Then I get the following error

OSError: [Errno 22] Invalid argument

Both are in str then why is not taking variable with a string value, but a string value in itself ??

Filenames cannot contain : characters.

You could do:

filename = datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S.%f")+"LOG.log"

Here you format the string yourself and in that way make sure the filename doesn't contain illegal characters.

Result:

2021-11-01_14.10.46.091188LOG.log

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM