serhii.net

In the middle of the desert you can say anything you want

15 Sep 2022

Python logging to file and screen with different loglevels

Goal: log everything to file, but show only part of the info on the screen. Previously: 220914-2249 Python logging change level through context manager and operator magic

My current understanding:

format = "[%(asctime)s %(name)s:%(lineno)s %(levelname)s]: %(message)s"

# Set it up, no handlers -> no default StreamHandler
# this loglevel is the one handlers will have access to!
logging.basicConfig(
	level=logging.DEBUG,
	handlers=[]
)
# Format, if we don't do this will be literally none
fmtr = logging.Formatter(fmt=format)

sh = logging.StreamHandler()
fh = logging.FileHandler("debug.log")

fh.setFormatter(fmtr)
sh.setFormatter(fmtr)

# Screen output set to whatever we want, fh to debug
sh.setLevel(loglevel)
fh.setLevel(logging.DEBUG)

# Add both handlers to root, both get propagated to logger etc.
logging.getLogger('').addHandler(sh)
logging.getLogger('').addHandler(fh)

Even though i did logger = logging.getLogger(__package__) at the very top of the file before the above bits, I can do logger.debug() etc. and it follows these settings. Nice.

Nel mezzo del deserto posso dire tutto quello che voglio.
comments powered by Disqus