Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 942
Aman Jaiswal Avatar asked Jun 22 '18 06:06

Aman Jaiswal


1 Answers

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')
like image 61
Hayat Avatar answered Oct 12 '22 08:10

Hayat