Logging basicConfig not creating log file when I run in PyCharm?

41,208

Solution 1

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.

Python 3.8: A new option, force, has been made available to automatically remove the root handlers while calling basicConfig().
For example:

logging.basicConfig(filename='ramexample.log', level=logging.DEBUG, force=True)`

See logging.basicConfig parameters:

force: If this keyword argument is specified as true, any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments.

Solution 2

I can't remember where I got this otherwise I would have provided a link. But had the same problem some time ago using in jupyter notebooks and this fixed it:

import logging
logger = logging.getLogger()
fhandler = logging.FileHandler(filename='mylog.log', mode='a')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fhandler.setFormatter(formatter)
logger.addHandler(fhandler)
logger.setLevel(logging.DEBUG)

Solution 3

The answer why this error happens is this:

The call to basicConfig() should come before any calls to debug(), info() etc.

If you do so the basicConfig can not create and write a new file. Here I called logging.info() right before logging.basicConfig().

Don't:

import logging
logging.info("root") # call to info too early
logging.basicConfig(filename="rec/test.log", level=logging.DEBUG) # no file created

Solution 4

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

Solution 5

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)
Share:
41,208
Ramnath Reddy
Author by

Ramnath Reddy

I am a python developer

Updated on July 09, 2022

Comments

  • Ramnath Reddy
    Ramnath Reddy almost 2 years

    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 the same code (with different filename='ram.log') in PyCharm it's 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?

    • Thijs van Dien
      Thijs van Dien about 9 years
      Perhaps PyCharm sets a different working directory, meaning the file ends up in another place. Try providing a full path.
    • Vikas Ojha
      Vikas Ojha about 9 years
      Your second block of code works perfectly fine and creates a log file for me in PyCharm.
    • Ramnath Reddy
      Ramnath Reddy about 9 years
      I provide a full path like below logging.basicConfig(filename='home/ra/myapp1.txt', level=logging.INFO) logging.info('Started') But No file was created
    • Maximas
      Maximas about 9 years
      @RamnathReddy Have you tried .log instead of .txt with the full file path? Did you also try an ls/pwd/dir to find out where the terminal is?
  • mallet
    mallet over 6 years
    would filename = ''.join([os.getcwd(),'ram.log']) be shorter and easier to read?
  • Marcello Romani
    Marcello Romani over 6 years
    This did indeed solve the problem for me. I suspect the issue is a conflict between basicConfig() and a "proper" logging setup elsewhere in the code (I use basicConfig() in tests and a different setup in the regular code). Thanks!
  • Shoonya
    Shoonya about 5 years
    @zwep , it works because as per the documentation docs.python.org/3/library/logging.html#logging.basicConfig , "This function does nothing if the root logger already has handlers configured for it."
  • stelios
    stelios over 4 years
    @salhin That's relative to the working directory instead of the source code directory, so it depends on what you are trying to achieve.
  • Adam Hughes
    Adam Hughes about 4 years
    For what it's worth, I had the same issue when my code had top-level imports that created a different logger. So even if you main module begins with logging.basicConfig it's quite possible you have logging.info/debug statements elsewhere in you project that are being run first via imports.
  • GoodJuJu
    GoodJuJu over 3 years
    Welcome to SO! Please read the tour tour and How to Answer a question. The question was asked 5 years ago.
  • Admin
    Admin about 3 years
    Yes it solved my problem...perhaps a common scenario is that one changed the order of code so some logging.info() gets before logging.basicConfig().
  • brygid
    brygid almost 3 years
    adding the full path after the filename helps!
  • snakecharmerb
    snakecharmerb over 2 years
    This solution is already provided is this existing answer. When answering old questions, please ensure your answer provides a distinct and valuable contribution to the Q&A.