How to completely reset Python stdlib logging module in an ipython session?

2024/10/10 22:25:20

I'd like to make repeated calls to Python scripts using %run in an ipython session, and for each of those scripts to log based on cmdline arguments passed via %run.

For example while debugging cmd.py I might over time want to run:

%run cmd.py
... logs with default behavior, e.g. to STDERR with root level WARN%run cmd.py --log_level DEBUG --log_file /tmp/cmd.out
... logs with root level DEBUG to a file%run cmd.py --log_level ERROR

Unfortunately this is difficult because the logging state created by logging.basicConfig persists after the first %run command (as is more generally true of all modules, and often desirable when using %run).

I realize that in full generality a series of %run commands like above will not be the same as running each command in a new process. However, it would be very convenient if things like the log_level and log_file could be re-initialized.

I've tried something like this in cmd.py:

import logging_config  # parse logging config from sys.argv
reload(logging_config) # re-parse cmdline if using %run multiple times

and logging_config.py does (condensed):

if logging_initialized:logging.getLogger().setLevel(lvl)
else:logging.basicConfig(level=lvl)logging_initialized = True

It works for simple cases but not if cmd.py imports libraries that also use logging. I've also experimented with logging.shutdown() (called at conclusion of each cmd.py) but that does not seem to help.

Answer

Don't use basicConfig() for this style of usage - it's meant for simple one-off configuration and, as the documentation says, subsequent calls after the first have no effect (it only does anything if the root logger has no handlers). This will be fine when your script is run from the shell prompt, but not from the interactive interpreter, IPython, IDLE, PythonWin, or other similar environment where the process you're interacting with doesn't exit.

Instead, use programmatic configuration, or fileConfig() or dictConfig() - these have modes where the completely replace the existing logging configuration with a new one.

https://en.xdnf.cn/q/69843.html

Related Q&A

I think Librosa.effect.split has some problem?

firstly, this function is to remove silence of an audio. here is the official description:https://librosa.github.io/librosa/generated/librosa.effects.split.htmllibrosa.effects.split(y, top_db=10, *karg…

Replace None in list with leftmost non none value

Givena = [None,1,2,3,None,4,None,None]Id likea = [None,1,2,3,3,4,4,4]Currently I have brute forced it with:def replaceNoneWithLeftmost(val):last = Noneret = []for x in val:if x is not None:ret.append(x…

Generating lists/reports with in-line summaries in Django

I am trying to write a view that will generate a report which displays all Items within my Inventory system, and provide summaries at a certain point. This report is purely just an HTML template by the…

How to test if a view is decorated with login_required (Django)

Im doing some (isolated) unit test for a view which is decorated with "login_required". Example:@login_required def my_view(request):return HttpResponse(test)Is it possible to test that the &…

Filter Nested field in Flask Marshmallow

I want to filter the nested field with is_active column as True in Marshmallow 3 Consider following scenario I have 3 tablesusers (id, name) organizations (id, name) organization_user(id, organization_…

Copy signature, forward all arguments from wrapper function

I have two functions in a class, plot() and show(). show(), as convenience method, does nothing else than to add two lines to the code of plot() likedef plot(self,show_this=True,show_that=True,color=k,…

How to fit a line through a 3D pointcloud?

I have a cable I am dropping from moving vehicle onto the ground. Using a camera system I estimate the location where the rope touches the ground in realtime. Movement of the vehicle and inaccuracy in …

Websockets with Django Channels on Heroku

I am trying to deploy my app to heroku. The app has a simple chatting system that uses Websockets and django channels. When I test my app using python manage.py runserver the app behaves just as intend…

How can I get the name/file of the script from sitecustomize.py?

When I run any Python script, I would like to see the scripts filename appear in the Windows command line windows titlebar. For example, if I run a script called "mytest.py", I want to see &q…

Sending Godaddy email via Django using python

I have these settings EMAIL_HOST = smtpout.secureserver.net EMAIL_HOST_USER = [email protected] EMAIL_HOST_PASSWORD = password DEFAULT_FROM_EMAIL = [email protected] SERVER_EMAIL = [email protected] EM…