Python, Choose Logging Files' Directory

I am using the Python logging library and want to choose the folder where the log files will be written.

For the moment, I made an instance of TimedRotatingFileHandler with the entry parameter filename="myLogFile.log" . This way myLogFile.log is created on the same folder than my python script. I want to create it into another folder.

How could I create myLogFile.log into , let's say, the Desktop folder?

Thanks, Matias

4 Answers

Simple give a different filename like filename=r"C:\User\Matias\Desktop\myLogFile.log

6

Let's say logs directory is in the parent directory of the current directory then you can use below 2 lines, to provide that location irrespective of the underlying os.

import os
log_dir = os.path.join(os.path.normpath(os.getcwd() + os.sep + os.pardir), 'logs')
log_fname = os.path.join(log_dir, 'log_file_name.log')

Specify an absolute path when creating instance TimedRotatingFileHandler:

from logging.handlers import TimedRotatingFileHandler
h = TimedRotatingFileHandler('/home/user/Desktop/myLogFile.log')

or

from logging.handlers import TimedRotatingFileHandler
h = TimedRotatingFileHandler('C:\\Users\\user\\Desktop\\myLogFile.log')
2

This is how I soleved it in linux.

# log_cfg.yaml
handlers:
    file_handlers:
        ...
        filename = log//error.log
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest