Ramnath Reddy
Ramnath Reddy

Reputation: 645

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

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?

Upvotes: 59

Views: 74650

Answers (8)

Neur0
Neur0

Reputation: 407

The answer why this error happens is this:

The call to basicConfig() should come before any calls to debug(), info() etc. Otherwise, those functions will call basicConfig() for you with the default options.

If you do so the basicConfig can not create and write a new file, because the default existing stderr WARNING handler already exists. 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

Upvotes: 11

komal ware
komal ware

Reputation: 79

By using force it get solve. like logging.basicConfig(filename="test.log", force=True)

Upvotes: 7

Sukalpa Sursen
Sukalpa Sursen

Reputation: 29

I used to get this error, but I solved by adding force=True in basicConfig:

logging.basicConfig(level=logging.INFO,filename='C:\\Users\\sukal\\PycharmProjects\\Test\\Logs\\Automation.log',format=Log_Format,force=True)

Upvotes: 2

Seal
Seal

Reputation: 1531

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.

Upvotes: 151

Anil MK
Anil MK

Reputation: 1

import logging

class LogGen:
    @staticmethod
    def loggen():
        logger = logging.getLogger()
        fhandler = logging.FileHandler(filename='.\\logs\\automation.log', mode='a')
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fhandler.setFormatter(formatter)
        logger.addHandler(fhandler)
        logger.setLevel(logging.INFO)
        return logger

Upvotes: -2

noobie
noobie

Reputation: 2607

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)

Upvotes: 22

stelios
stelios

Reputation: 2845

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

Upvotes: 7

Maximas
Maximas

Reputation: 712

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)

Upvotes: 4

Related Questions