Hi guys,

I am trying to use the Python logging API to log only to a file. The code below logs to only a file if I have it at the beginning of my class, right beneath the "class ..." line. If, however, I put it inside a method, it logs to both a file AND the console. :( What am I doing wrong? At one point I thought that perhaps another class file, being launched later in a separate thread, which also calls logging, somehow was messing up the handler or logging (I have now understood that if you do logging.basicConfig(...) in another class file in the same Python interpreter instance, it'll suddenly mess up logging.basicConfig(...) stuff you'll have done in another file). But, having globally searched my entire application files, I am sure I am not modifying logging later. Thanks a lot for any help.

formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler = logging.FileHandler('/DifRec.txt')
handler.setFormatter(formatter)
fileLogger = logging.getLogger('DIFRECFILE')
fileLogger.addHandler(handler)
fileLogger.setLevel(logging.INFO)

fileLogger.info("Sending message...")

It sounds like you want to modify the root logger, so fileLogger = logging.getLogger('DIFRECFILE') should be fileLogger = logging.getLogger('') to get the root logger instead of creating a new one.

Explaination:
Your problem is coming from your 4th line. When you call logging.getLogger('DIFRECFILE') it will try to find a logger named 'DIFRECFILE' and if it doesn't find it, it creates a logger by that name. So after line 4 you have two loggers: root (which prints to the console)and 'DIFRECFILE' (which writes to a file).

Hope this helps

Nix that last message, tried it out and it didn't work. What I've done is globally call logging.basicConfig() so there will be only one call to that function. Then messages will be logging.info("This is a message...")

Hmm, this didn't solve the problem. I am still quite confused about logging and will post a new post. I just want one logger to log to a file, and another to log to console. Also, neither should log the other's logging messages. I have read and re-read the Python documentation but not found an explanation of how to do this. Thanks anyways.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.