Change default location log file generated by logger in python

Aman Jaiswal picture Aman Jaiswal · Jun 22, 2018 · Viewed 18.7k times · Source

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

Answer

Hayat picture Hayat · Jun 22, 2018

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