I have a third party python console script, which source I don't want to modify.
But I want to configure the logging which is done by the script and its libraries. The script uses the standard python logging, but does not support configuration of it.
The script uses this pattern:
import logging
logger=logging.getLogger(__name__)
Use cases:
- I want INFO messages of file foo.py to be ignored.
- I want to include the PID in the loggings messages.
How can I configure the logging, if I don't want to modify the sources of the console script?
The script gets called via cron
.
How can I configure the logging if this script?
Important
Creating a wrapper script like in this answer is not a solution for me.
The linux process hierarchy looks like this:
Cron -> third_party_script
There should be any "glue", "wrapping" or "dirty-hack" script between cron and third_party_script
.
Why obtrusive/netpicking?
I want to practice "separation of concerns". I want to be able to configure logging one time and in one place. This configuration should get used by all python code of a virtualenv. Writing a wrapper would be a work-around. I want a solution.
You can change the minimum log level of that logger.
Now, only WARNING and above will be shown. No INFO and no DEBUG.
Addionally, you could also change the format.
%(process)d
being the PID.All together:
Note: You should replace
__name__
in your code with the relevant log handler.Several possibilities:
Wrapper
If you can edit your cron table you could create a small script in python that get the lib logger, remove the existing log handler and hook your custom handler on it:
Also keep in mind this suppose the lib does not re-declare the logger on the way.
Dynamic code edit
If you do not have the possibility to modify the cron call, you might be able to do dynamic code edit but that is equivalent to editing the file by hand (hacky):
I asked this question several months ago. Unfortunately I got no answer which satisfied me.
The distinction between using logging and setting it up is important for me.
This is my solution: In our context we set up logging in a method which gets called in
usercustomize.py
.This way the optional plugins can use the logging without the need to set it up.
This almost solved all my needs.
Up to now I found no better way than
usercustomize.py
. My perfect solution would be something I would callvirtualenvcustomize.py
: Some initialization code which gets run if the interpreter loads virtualenv. Up to now I could not find such a hook. Please let me know if you have a solution.A library isn't supposed to configure logging - that's up to the application developer. Inbar Rose's answer isn't quite right. If the module you're referring to is called
foo
, then the reference to__name__
in itsgetLogger
call will be passing infoo
. So in your configuration code, you would need to do the equivalent ofTo include the PID in the logs, just ensure that you use an appropriate format string for your Formatters, i.e. one which includes
%(process)d
. A simple example would be:Note that you can't write to the same log file from multiple processes concurrently - you may need to consider an alternative approach if you want to do this.
Update: An application developer is someone who writes Python code which is not the library, but is invoked by e.g. a user or another script via a command line or other means of creating a Python process.
To use the code I posted above, there is no need to wrap or modify the third-party code, as long as it's a library. For example, in the main script which invokes the third-party library:
If the third party code runs via cron, it's not library code - it's an application, and you are probably out of luck.
tl;dr
In a nutshell, what we want to do is to inject code that gets executed by the python interpreter before our main code gets executed.
The best way to achieve this is to create a virtualenv and add
sitecustomize.py
in the virtualenv's site-packages.Demonstration
Let's assume that the application we want to run is called
my_app.py
and that its logger has the same name.Running
my_app.py
should only show the messages whose severity is >WARNING
(which is the default behavior in python's logging).Now let's create a virtual environment
And let's add
sitecustomize.py
to the virtualenv's site packages.Now let's try to run
my_app.py
using the virtualenv:And that was all) We got proper logging without having to modify
my_app.py
or write a wrapper!Now if you want to know why this is the optimal approach, keep on reading.
(Really) long answer
Before understanding why using a virtualenv +
sitecustomize.py
is the correct approach to this problem, we need to make a not so short introduction.Note: I am going to assume that you create virtual environments using the
venv
module which uses stdlib'ssite.py
. Thevirtuaelnv
library, uses its ownsite.py
and might be doing things slighly differently. Nevertheless, after reading this answer you should be able to examine if there are any differences betweenvenv
andvitualenv
and understand how to handle them.What are
site-packages
The short answer is that
site-packages
is the place where python installs 3rd party code (as in non-stdlib code). For more info read this and the provided links.How to inject code?
Python does allow you to customize the python interpreter while it starts up, i.e. before our main code/script/whatever gets executed. This can be useful for e.g.:
The way you achieve the injection is by creating/modyfing either
sitecustomize.py
orusercustomize.py
. You can also use a "path configuration file" (i.e.*.pth
) file with an import statement but I will not cover this case here since:sitecustomize
/usercustomize
.Anyway, if you need more info WRT to path configuration files you can check PyMOTW and if you want an example of using them with import statement check this blog post.
sitecustomize
&usercustomize
So,
sitecustomize
andusercustomize
are special files that don't exist by default, but if we create them python will automatically import them before it starts to execute our code. We can create these files:/usr/lib/python3.7/site-packages/
)~/.local/lib/python3.7/site-packages/
)sitecustomize
is always imported beforeusercustomize
. If either file is missing, theImportError
is silently ignored.As a security precaution, if there is a mismatch between user or group id and the effective id, then user site-packages are disabled (source). Moreover, the python interpreter has CLI arguments that either completely disable site-packages (both system and user ones) or disable user site-packages. Assuming that we don't have an id mismatch and that we don't use any CLI flags, then user site-packages have higher priority than system site-packages. So if we have both:
the first one is the one that will be imported. We can actually check the sys.path priority by executing the
site.py
module:The important information here is the value of
ENABLE_USER_SITE
. If it isTrue
then user site-packages are enabled. If itFalse
then we can only use global site-packages. E.g. if we usepython -s
:Note that in this case
ENABLE_USER_SITE
isFalse
.Just for completeness, let's completely disable the site-packages:
Experiment
In order to better understand this, let's do an experiment. First let's create
usercustomize
sitecustomize
modules in both system and user site-packages.WARNING: We will be creating files in system site-packages. This will be interfering with your python distribution. Be careful and REMEMBER to remove them when we are done.
Let's also create a python module:
Now let's execute
foo.py
:As we can see:
sitecustomize
andusercustomize
are being importedNow what will happen if we disable user site-packages?
This time we see that we:
sitecustomize
is being imported. Even thoughusercustomize
exists in system site-packages python does not import it! This is important! Keep it mind for when we discuss virtualenvs! (TIP: this has to do withENABLE_USER_SITE
; do you remember what value does it have in this case?)sitecustomize
is being imported from system site-packagesFinally, if we completely disable site-packages, obviously
usercustomize
andsitecustomize
will be ignored:What about virtualenvs?
OK, now let's bring virtualenv's into the game too. There are two types of virtualenvs:
--system-site-packages
.Let's create virtualenvs of both types
Let's also create
sitecustomize.py
andusercustomize.py
modules into the virtualenv's site-packages:and let's see the differences:
What do we see here? That on normal virtualenv's
ENABLE_USER_SITE
isFalse
, which means that:sitecustomize
is being imported! I.e. we can't useusercustomize
to inject code!!!We can also see that instead of our global site-packages, the virtualenv is using its own one (i.e.
/tmp/test/venv_no_system/lib/python3.7/site-packages
).Now let's repeat this but this time with the virtualenv that uses the system site-packages:
In this case, the behavior is different...
ENABLE_USER_SITE
isTrue
which means:usercustomize
is being imported normally.But there is also one more difference. In this case we have 3 site-packages directories. The virtualenv one is the one with the higher priority followed by the user site-packages while the system site-packages is the last one.
So what to use?
I think that there are three options:
I think that in the majority of the cases, e.g. on normal servers/desktops, modifying the system python installation should generally be avoided. At least on *nix, too many things depend on Python. I would be really reluctant to change its behavior. Possible exceptions are ephemeral or static "systems" (e.g. inside a container).
As far as virtual environments go, unless we know we are going to need system site-packages, I think it makes sense to stick with the current practise and use normal ones. If we adhere to this, then in order to inject code before our script gets executed we only have one option:
Cleaning up