freddy888
freddy888

Reputation: 1010

Python Logging only to console not to file

I run my python 3.7 program in an infinite loop and when the log file gets very big, logging drags a lot of cpu power. Consequently, I want my logs just be printed out to the console instead of written to a file. I know I can use print for that, but I prefer logging.

Here is what I use at the moment:

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s % 
(message)s',
                    datefmt='%m-%d %H:%M%S',
                    filename='mylogfile.log',
                    filemode='w')

console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s % 
(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
logger = logging.getLogger('')

Then I use the module like that:

logger.error('error in X')  

Is there anything that I can use to prevent the logging module from writing to file?

Upvotes: 2

Views: 4275

Answers (1)

Sosel
Sosel

Reputation: 1718

I am not an expert, but my solution works for me (writing only into the console):

logger = logging.getLogger("MyApp")
logger.setLevel(logging.DEBUG)

# remove all default handlers
for handler in logger.handlers:
    logger.removeHandler(handler)

# create console handler and set level to debug
console_handle = logging.StreamHandler()
console_handle.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter("%(name)-20s - %(levelname)-8s - %(message)s")
console_handle.setFormatter(formatter)

# now add new handler to logger
logger.addHandler(console_handle)

Upvotes: 6

Related Questions