Aman Jaiswal
Aman Jaiswal

Reputation: 1093

Change default location log file generated by logger in python

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')

Upvotes: 14

Views: 53931

Answers (4)

richie101
richie101

Reputation: 21

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()]
                )

Upvotes: 1

mashrur
mashrur

Reputation: 43

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")

Upvotes: 2

Hayat
Hayat

Reputation: 1639

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')

Upvotes: 17

Raghav Patnecha
Raghav Patnecha

Reputation: 736

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

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

Upvotes: 1

Related Questions