When I run the following Python 3 code in CMD or Powershell :
# -*- coding: utf-8 -*-
import time
logging.config.fileConfig('log_config.ini',
defaults={'logfilename': time.strftime(str(__file__.split(".")[0].split("/")[-1]) + "_%Y%m%d-%H%M%S.log", time.localtime())})
I get the following error :
Traceback (most recent call last):
File "C:\Users\test.py", line 6, in <module>
defaults={'logfilename': time.strftime(str(__file__.split(".")[0].split("/")[-1]) + "_%Y%m%d-%H%M%S.log", time.localtime())})
File "C:\Python37-32\lib\logging\config.py", line 79, in fileConfig
handlers = _install_handlers(cp, formatters)
File "C:\Python37-32\lib\logging\config.py", line 142, in _install_handlers
args = eval(args, vars(logging))
File "<string>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 16-17: truncated \UXXXXXXXX escape
However, I don't meet this problem with PyCharm.
This is my log configuration file :
# Configuration
[logger_root]
level = DEBUG
handlers = consoleHandler, fileHandler
# ========================================= DECLARATIONS
[loggers]
keys = root
[handlers]
keys = consoleHandler,fileHandler
[formatters]
keys = simpleFormatter
# ========================================= DEFINITION DES HANDLERS
# Le handler par défaut écrit dans la console...
[handler_consoleHandler]
class = StreamHandler
level = DEBUG
formatter = simpleFormatter
args = (sys.stdout,)
# ...et un handler plus axé production qui écrit dans un fichier
[handler_fileHandler]
class = handlers.TimedRotatingFileHandler
level = INFO
formatter = simpleFormatter
args = ('logs/%(logfilename)s', 'D', 1, 30)
# ========================================= DEFINITION DES FORMATTERS
# Le formatter utilisé de façon standard
[formatter_simpleFormatter]
format = [%(asctime)s] - [%(levelname)s] - [%(name)s] - [%(filename)s:%(lineno)s] - %(message)s
If someone has encountered the same problem with a solution.
In PyCharm, __file__
returns a string with "/".
While in CMD and powershell, __file__
returns a string with "\".
We have just to add .replace("\\", "/")
after __file__
:
# -*- coding: utf-8 -*-
import time
logging.config.fileConfig('log_config.ini',
defaults={'logfilename': time.strftime(str(__file__.replace("\\", "/").split(".")[0].split("/")[-1]) + "_%Y%m%d-%H%M%S.log", time.localtime())})