Python logging in different systems show different format/level
I have a simple command line program written in python. The program logs to screen using the logging module configured in the following way:
logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s')
The weird thing is that in my laptop, the program logs at the right level (INFO) an with the desired format, while when I run the program in a server the program only logs errors and warnings with another format.
In both systems I am running Python 2.7 inside a virtual environment. The environments are not exactly the same.
I think that some module is changing my configuration. I do not understand why it happens only in the server, but is there any way, to开发者_如何转开发 find which one?
Thanks in advance,
The basicConfig()
API in logging will do nothing (as documented) if the root logger already has handlers configured. Your basicConfig()
call may be being ignored because some other code in the server has already configured some handlers for the root logger.
In general library code should not add handlers - that's the application developer's responsibility. However if you are e.g. developing a web application using a framework, the framework may already have configured some handlers.
You say "on the server", but it's not clear whether you're talking about a service application or just running a utility script on a machine which happens to be a server. As you say, the virtual envs are slightly different, so the difference between them might be the place to look for a hint.
To find out what's configuring handlers on the root logger, you could grep the relevant sources for basicConfig()
or addHandler()
.
Alternatively, you could explicitly add a handler rather than relying on basicConfig()
to do it for you:
f = logging.Formatter('%(levelname)-8s %(message)s')
h = logging.StreamHandler()
h.setFormatter(f)
logging.getLogger().addHandler(h)
but this may result in multiple messages if other console handlers are also added to the root logger.
If you think it's a certain module, try freezing the code, using cx_freeze, or Py2exe. That'll create and executable file, and it'll put the modules it requires in it so it won't be dependent on the modules on system.
The python logging system configuration is unique in a python process. If somebody change the logging configuration in a process, all the logs produced in this process will follow this configuration.
精彩评论