Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use python's logging to log to the screen and to a file

I want to log using python's logging to both the screen and a file

this is how I log to the screen:

import logging
logging.basicConfig(level=logging.DEBUG)    
logging.debug('hello')

and this is how I log to a file:

import logging
logging.basicConfig(level=logging.DEBUG,filename='a.log')   
logging.debug('hello2')

Is there a way to log to both the file and the screen? preferably using logging.basicConfig

I am using python 2.7.14

like image 575
Goolmoos Avatar asked Dec 18 '22 00:12

Goolmoos


1 Answers

If you want one logger for the screen and one for the log file, try this:

import logging


log = logging.getLogger('logger')
log.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(message)s')

fh = logging.FileHandler('test.log', mode='w', encoding='utf-8')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
log.addHandler(fh)

ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)
log.addHandler(ch)

This creates two log handlers. When you call log.debug/info/warning etc, it will log to each of your handlers. If the level they are set at is the same or higher, it will log the message, otherwise it won't.

In this example calling log.debug("test message") will save the str "test message to test.log, but you will not see the output on the screen because the StreamHandler()'s level is above the debug debug.

When you call log.info("test message"), it will save the str "test message to test.log and output it to the console because StreamHandler()'s level is info

log.setLevel(logging.DEBUG) ensures that everything will be logged. If you exclude this line, the default of WARNING will be enforced, and even if you set the level lower in a separate handler, you won't be able to log anything >= that level

The levels for logging are as follows:

DEBUG
INFO
WARNING
ERROR
CRITICAL
like image 62
Mattwmaster58 Avatar answered Jan 19 '23 00:01

Mattwmaster58