alex
alex

Reputation: 7433

Specifying a custom logging Linux filepath in Python 2

I'm trying to understand how logfiles work with the Python 2 logging module.

I know that I can save the log output to a text file using something like:

logging.basicConfig(filename='example.log',level=logging.DEBUG)

It's not clear to me from the documentation on:

  1. Whether or not absolute filename paths are valid
  2. The proper syntax for specifying relative paths (assuming that ../example.log is valid).

If I execute this script from /home/bob, how do I specify that I want the logfile saved to the /tmp directory instead - using both absolute and relative paths?

Is logging.basicConfig(filename='../../tmp/example.log') valid?

Similarly, is logging.basicConfig(filename='/tmp/example.log') valid?

Upvotes: 1

Views: 1909

Answers (2)

Tristan
Tristan

Reputation: 2088

They are both valid. But relative paths (with ..) will select different files depending on the directory you are in when you run it.

So when you run logger.py in /home/user/projects/python and the filename is ../log.txt the file will be saved in /home/user/projects. On the other hand when you run the script in /home/user then log.txt will be saved in /home/.

Absolute paths always work and are more reliable. If you want a file in the current directory I recommend this approach:

basedir = os.path.abspath(os.path.dirname(__file__))
filename = os.path.join(basedir, 'file.txt')

Upvotes: 1

Chen A.
Chen A.

Reputation: 11280

When stating just the filename, it would be written to the current directory. Using Python IDLE you can check that as follows

>>> import logging
>>> logging.basicConfig(filename='relative.log')
>>> logging.info('test')

C:\Python27\relative.log

My working dir is Python27, and I have a file there named relative.log with my logged message.

When you change the file location to ../relative.log, I get a new file at the parent directory of Python27. So relative path does work for logging:

>>> import logging
>>> logging.basicConfig(filename='../relative.log')
>>> logging.info('test123')

C:\relative.log

And logging module also supports absolute path:

>>> logging.basicConfig(filename=r'c:\abs_path.log')
>>> logging.info('test')

C:\abs_path.log

It is always better to use absolute path, as explicit is better than implicit.

Upvotes: 2

Related Questions