aAnnAa
aAnnAa

Reputation: 145

Prevent Python logger from printing to console

I'm getting mad at the logging module from Python, because I really have no idea anymore why the logger is printing out the logging messages to the console (on the DEBUG level, even though I set my FileHandler to INFO). The log file is produced correctly. But I don't want any logger information on the console. Here is my configuration for the logger:

template_name = "testing"
fh = logging.FileHandler(filename="testing.log")
fr = logging.Formatter("%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s")
fh.setFormatter(fr)
fh.setLevel(logging.INFO)
logger = logging.getLogger(template_name)
# logger.propagate = False # this helps nothing
logger.addHandler(fh)

Would be nice if anybody could help me out :)

Upvotes: 6

Views: 11458

Answers (3)

Wouter van Reeven
Wouter van Reeven

Reputation: 11

Yet another way of doing this is to first create your FileHandler and then call the basicConfig method, like this

import logging

template_name = "testing"
fh = logging.FileHandler(filename="testing.log")
logger = logging.getLogger(template_name)
logging.basicConfig(
    format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s",
    level=logging.INFO,
    handlers=[fh],
)
logger.info("Test")

Upvotes: 0

DEner
DEner

Reputation: 95

I found this question as I encountered a similar issue, after I had removed the logging.basicConfig(). It started printing all logs in the console.

In my case, I needed to change the filename on every run, to save a log file to different directories. Adding the basic config on top (even if the initial filename is never used, solved the issue for me. (I can't explain why, sorry).

What helped me was adding the basic configuration in the beginning:

logging.basicConfig(filename=filename,
                        format='%(levelname)s - %(asctime)s - %(name)s - %(message)s',
                        filemode='w',
                        level=logging.INFO)

Then changing the filename by adding a handler in each run:

file_handler = logging.FileHandler(path_log + f'/log_run_{c_run}.log')
formatter    = logging.Formatter('%(asctime)s : %(levelname)s : %(name)s : %(message)s')
file_handler.setFormatter(formatter)
logger_TS.addHandler(file_handler)

Also curious side-note. If I don't set the formater (file_handler.setFormatter(formatter)) before setting the handler with the new filename, the initially formated logging (levelname, time, etc.) is missing in the log files.

So, the key is to set the logging.basicConfig before, then set the add the handler. As @StressedBoi69420 indicated above.

Hope that helps a bit.

Upvotes: 3

Daniel Haley
Daniel Haley

Reputation: 52858

You should be able to add a StreamHandler to handle stdout and set the handlers log level to a level above 50. (Standard log levels are 50 and below.)

Example of how I'd do it...

import logging
import sys

console_log_level = 100

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s",
                    filename="testing.log",
                    filemode="w")
console = logging.StreamHandler(sys.stdout)
console.setLevel(console_log_level)
root_logger = logging.getLogger("")
root_logger.addHandler(console)

logging.debug("debug log message")
logging.info("info log message")
logging.warning("warning log message")
logging.error("error log message")
logging.critical("critical log message")

Contents of testing.log...

2019-11-21 12:53:02,426,426 root INFO info log message
2019-11-21 12:53:02,426,426 root WARNING warning log message
2019-11-21 12:53:02,426,426 root ERROR error log message
2019-11-21 12:53:02,426,426 root CRITICAL critical log message

Note: The only reason I have the console_log_level variable is because I pulled most of this code from a default function that I use that will set the console log level based on an argument value. That way if I want to make the script "quiet", I can change the log level based on a command line arg to the script.

Upvotes: 0

Related Questions