Peter Chao
Peter Chao

Reputation: 443

logging directory format?

I want to log my test result one level above from where I am running the test. So I how do I do it without list out the entire path?

logging.basicConfig(filename="test.log", level=logging.DEBUG)

Upvotes: 0

Views: 3362

Answers (1)

This was more than a trivial question for me to figure out - "via Google" yielded many options, but using your current code, here are two possible solutions:

  • continue using logging.basicConfig: the trivial solution would be add the relative path of the directory one level above to the filename. The pythonic and cross-platform way appears to be with os.pardir:
import os
import logging

# setup the path to the logfile
logname = 'test.log'
logfile = os.path.join(os.pardir, logname)

# log as you are currently
logging.basicConfig(filename=logfile, level=logging.DEBUG)
  • Another option would be to use logging.FileHandler, which python docs state:

    Handlers send the log records (created by loggers) to the appropriate destination.

    which in this case would be the location one level above from where you're running the test. Only difference is you'd use the newly created logger object:

#setup the logger object
logger = logging.getLogger('test')
fh = logging.FileHandler(logfile)
logger.addHandler(fh)
logger.setLevel(logging.DEBUG)

# use the logger object
logger.debug('a DEBUG')
logger.info('an info')

Upvotes: 2

Related Questions