Python’s standard logging
library offers a standard module (logging.config
) for configuration, and it offers a lot of options. Most of them look like a pain. If you just want to configure the logging level, for example, you might wonder: Do I have to write an entire file listing handlers and files and other configuration options just to say I only want to see INFO
-level messages and above?
Fortunately, there’s a much easier way to configure your code’s logging level. You can simply call logging.basicConfig()
with the configuration settings you want to change. In this case, you’ll want something like:
import logging
import os
...
def main():
...
logging.basicConfig(
level=getattr(logging, os.getenv("LOGGING_LEVEL", "INFO"))
)
This call to basicConfig()
will set the logging level to the one defined by the environment variable LOGGING_LEVEL
(which could be, for example, ERROR
, WARNING
, INFO
, or DEBUG
by default). If the user doesn’t set LOGGING_LEVEL
, it defaults to the INFO
level.
Of course, we don’t have to get the logging level config from an environment variable—it could come from anywhere. If this is a CLI app, you could define a --logging-level
argument that controls the logging level. You could define and load your own simple configuration file (perhaps a json
file) that includes a logging level value. The sky’s the limit.
So, don’t worry about setting up a complicated logging config file. You can easily configure logging with a simple call to basicConfig()
.
Leave a Reply