I am create a decently complex program and need to add logging to the whole thing. For this I have created a separate file which allows me to easily create a new logger with everything I need for it. Though I am experiencing problem with getting the absolute path of the log folder since the path is returned as a string.
The code here is the code I used to detect which OS it is loaded on, and this works fine, maybe there is a better way to achieve what I am trying to do here, but for now I am having issues of the last backslash in the win32
OS not returning with the entire path
def __get_logging_path(log_folder):
if sys.platform == 'win32':
return os.path.abspath(os.path.join(os.path.dirname(__file__)) + f'\\{log_folder}\\')
elif sys.platform == 'linux':
return os.path.abspath(os.path.join(os.path.dirname(__file__) + f'/{log_folder}/'))
else:
raise OSError(f'Untested OS: {sys.platform}')
I have tried a couple things to replace the following code
return os.path.abspath(os.path.join(os.path.dirname(__file__)) + f'\\{log_folder}\\')
Below are all the different option I have tried an none of them have worked so far
return os.path.abspath(os.path.join(os.path.dirname(__file__)) + '\\' + log_folder + '\\')
return os.path.abspath(os.path.join(os.path.dirname(__file__)) + r'\\' + log_folder + r'\\')
return os.path.abspath(os.path.join(os.path.dirname(__file__)) + f'\\{log_folder}' + r'\\')
There is a couple more, but generally just don't work getting
Though I have not figured out what the issue with the original problem was, (old)
I did manage to get it working with the suggestion of using pathlib.Path
By looking in to the documentation a bit I managed to change the code above in to a single line of code
Path(__file__).parent.joinpath(log_folder, f'{file_name}.log')
This points to a .log file in a subdirectory of the directory of the currently executing file
EDIT:
I recently through comments I have found out my mistake. I managed to miss the fact that os.path.join()
creates a valid path from given strings, instead of joining the strings together.
Therefore the solution to the original problem seems to be as follows:
os.path.abspath(os.path.join(os.path.dirname(__file__), log_folder, log_file))