16

I am using logger in my python source code, and want to create logs on specific location but python logging module creates the log files at the default place i.e. from where it is executed.

Is there is any way to change this default location?

below is my configuration

  import logging
  logger = logging.getLogger(__name__)
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='testGene.log, filemode='w')
1
  • You should do your basicConfig call first, I think. Commented Aug 13, 2021 at 20:07

4 Answers 4

17

Try this:

import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='path/to/your/directory/testGene.log', filemode='w')

Or

import logging
import os
if not os.path.exists("Logs"):
    os.makedirs("Logs")
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='Logs/testGene.log', filemode='w')
Sign up to request clarification or add additional context in comments.

3 Comments

This will not work, when you run the python source code it will try to add below two location which will end up with error "No such file or directory" 1: path location of log file 2: location from where script is executed
@AmanJaiswal It will run if your platform is Linux. And by default, it will add path for the current working directory.
Please try to run given solution from multiple places and you will end up creating multiple folder, this will never going to target only one destination folder
2

Create a module name log_to_text_file.py with the following code:

import logging, logging.handlers
def get_logger(module_name):
    logger = logging.getLogger(module_name)
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s:%(levelname)s : %(name)s : %(message)s')
    file_handler = logging.FileHandler('//loglocation/application.log')
    file_handler.setFormatter(formatter)

    if (logger.hasHandlers()):
        logger.handlers.clear()
    logger.addHandler(file_handler)
    return logger

Import the module in the beginning of other modules and call the function like this:

log = get_logger(__name__)                                                    
log.info(f"this is info logging)
log.exception("This is exception logging")

1 Comment

yeah, root logger 's handlers is a empty list at beginning, if you have config it to output to a file and after a while you want to change the output destination to another file, you should call "logger.handlers.clear()" at first, otherwise "logging.basicConfig" may not take effect.
1

When initializing logger specify location where you want your logs to be saved.

logging.config.fileConfig('logging.config',
                      defaults={'yourlogfile': '/path/to/log/file'})

1 Comment

This will not work, when you run the python source code it will try to add below two location which will end up with error "No such file or directory" 1: path location of log file 2: location from where script is executed
1
import logging as log
import os

dir_path = os.path.dirname(os.path.realpath(__file__))

if not os.path.exists(dir_path+"/Logs"):
    os.makedirs(dir_path+"/Logs")

log.basicConfig(level=log.DEBUG,
                format='%(asctime)s: %(levelname)s [%(filename)s:%(lineno)s] %(message)s',
                datefmt='%d/%m/%Y %I:%M:%S %p',
                handlers=[log.FileHandler(dir_path+'/Logs/file_logs.log'),
                          log.StreamHandler()]
                )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.