Set Path for logger File Handler

Viewed 77

I try to set my logger to a folder on another server in my network, but the path I give the logging.FileHandler() function, always adds the current directory before my path. How can i prevent that?

#   initialize logger
currDate = str(date.today())
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s')
file_handler = logging.FileHandler("\\Server.de\Path\longer Path\Excel\LogFiles\Logger"+currDate+".log")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

The error I get is:

Traceback (most recent call last):
  File "c:\Users\HAKO\Documents\GitHub\PythonScripts\FTP_connect\DatenTransfer.py", line 326, in <module>
    file_handler = logging.FileHandler("\\Server.de\Path\longer Path\Excel\LogFiles\Logger"+currDate+".log")
  File "C:\Users\HAKO\AppData\Local\Programs\Python\Python310\lib\logging\__init__.py", line 1169, in __init__
    StreamHandler.__init__(self, self._open())
  File "C:\Users\HAKO\AppData\Local\Programs\Python\Python310\lib\logging\__init__.py", line 1201, in _open
    return open_func(self.baseFilename, self.mode,
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\HAKO\\Documents\\GitHub\\PythonScript\\Server.de\Path\longer Path\Excel\LogFiles\Logger2022-07-27.log'

Why does the Filehandler make:

"C:\Users\HAKO\Documents\GitHub\PythonScript\Server.de\Path\longer Path\Excel\LogFiles\Logger2022-07-27.log"

Out of

"\Server.de\Path\longer Path\Excel\LogFiles\Logger2022-07-27.log"

1 Answers

In Python, backslashes are escaped unless you use the raw string format. Try using

r"\Server.de\Path\longer Path\Excel\LogFiles\Logger"+currDate+".log"

Note the leading r, indicating that backslashes shouldn't be escaped.

Related