Logging basicConfig not creating log file when i r

2019-03-20 08:57发布

When i run below code in terminal its create a log file

import logging 
logging.basicConfig(filename='ramexample.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

but when i run samecode (with different filename='ram.log') in pycharm its not creating any log file . why?

import logging 
logging.basicConfig(filename='ram.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

What i have to do to create a log file with pycharm ?

3条回答
▲ chillily
2楼-- · 2019-03-20 09:44

Maximas is right. File path is relative to execution environment. However instead of writing down the absolute path you could try the dynamic path resolution approach:

filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ram.log')
logging.basicConfig(filename=filename, level=logging.DEBUG)

This assumes that ram.log resides in the same directory with the one that contains the above code (that's why __file__ is used for).

查看更多
Bombasti
3楼-- · 2019-03-20 09:47

This does create a log within the pycharm terminal using the Py terminal within it. You need to check the location of where the terminal is (try dir on Windows or pwd on linux/mac). Instead of just putting in ram.log, use the full file path of where you would like the file to appear. E.G.

logging.basicConfig(filename='/Users/Donkey/Test/ram.log', level=logging.DEBUG)
查看更多
时光不老,我们不散
4楼-- · 2019-03-20 09:59

I encountered same issue and found none of the answers previously provided here would work. Maybe this issue had been solved long ago to Ramnath Reddy, but I could not find the correct answer anywhere online.

Luckily, I found a solution from a colleague's code by adding the following lines before logging.basicConfig().

Remove all handlers associated with the root logger object.

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

Try and see if it helps for whomever had the same issue.

查看更多
登录 后发表回答