13

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')
Aman Jaiswal
  • 1,084
  • 2
  • 18
  • 36

4 Answers4

14

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')
Mansoor Siddiqui
  • 20,853
  • 10
  • 48
  • 67
Hayat
  • 1,539
  • 4
  • 18
  • 32
  • 1
    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 – Aman Jaiswal Jun 22 '18 at 07:40
  • @AmanJaiswal It will run if your platform is Linux. And by default, it will add path for the current working directory. – Hayat Jun 22 '18 at 11:49
  • 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 – Aman Jaiswal Jun 22 '18 at 11:53
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'})
Raghav Patnecha
  • 716
  • 8
  • 29
  • 1
    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 – Aman Jaiswal Jun 22 '18 at 07:41
1

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")
wovano
  • 4,543
  • 5
  • 22
  • 49
mashrur
  • 33
  • 1
  • 1
  • 6
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()]
                )
richie101
  • 21
  • 2