Comments (6)
could you meet the use case by logging the serialized values?
logger.debug(f"environment: {env.dump()}")
from environs.
env.dump()
only returns values that have already been retrieved (AFAIK). It would be difficult to know when to log that.
For example, if it's logged on application start, that may be too early and other environment variables could be read later in the application lifecycle.
If it's logged every time a value is looked up, then we may as well just log the retrieved value.
from environs.
are you reading envvars during app runtime? if so, i'll warn that that's not the intended use case. we recommend parsing all the environment variables at one time in a settings module (like in the flask example). that ensures that they all get validated before the app starts, and it would also make it easier to log the values.
from environs.
Generally speaking that's what we're doing (loading from Env
on startup), but they're not loaded centrally. During dependency injection, different services and modules are wiring in their own from a shared Env
object that gets passed around.
I guess we could add a log of env.dump()
at the end of dependency injection if that's your recommendation, but it just feels riskier to separate that information out from the points where Env
is actually accessed.
from environs.
Hello @jrouly , currently this is not implemented but you can overwrite the call and other methods with the decorated logged method to achieve the result you want. It's a bit hacky, here is a working example. It was fun to make, but I have to say it's not a good practice and I don't encourage this to be done in production code.
import functools
import logging
from environs import Env
def log_env_result(func, /, key_index):
logger = logging.getLogger("environs")
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
key = kwargs.get("name") or args[key_index]
logger.debug(f"Getting value for key {key}: '{result}'")
return result
return wrapper
class CustomLoggingEnv(Env):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# replace every single method with the decorated version
for field in [
"int", "bool", "str", "float", "decimal", "list", "dict", "json", "datetime", "date", "time",
"path", "log_level", "timedelta", "uuid", "url", "enum", "dj_db_url", "dj_email_url", "dj_cache_url"
]:
self.__setattr__(field, log_env_result(self.__getattribute__(field), key_index=0))
__call__ = log_env_result(Env.__call__, key_index=1) # since self is passed the key index is 1
env = CustomLoggingEnv()
env.read_env() # read .env file, if it exists
# nothing should print
env("GITHUB_USER", "hello world")
env.int("NUMBER_OF_RETRIES", "10")
# set logging on module to debug
logging.basicConfig()
logging.getLogger("environs").setLevel("DEBUG")
env("GITHUB_USER", "hello world")
env.int("NUMBER_OF_RETRIES", "10")
That produces:
DEBUG:environs:Getting value for key GITHUB_USER: 'hello world'
DEBUG:environs:Getting value for key NUMBER_OF_RETRIES: '10'
Process finished with exit code 0
from environs.
Related Issues (20)
- Environs powered yaml files HOT 3
- a list-type environment variable contains tuple-type elements HOT 3
- Can't reload The environment variables once you start the application
- RemovedInMarshmallow4Warning: The 'missing' argument to fields is deprecated
- dj-database-url is Out of date HOT 1
- env.url broken after 9.3.3 upgrade HOT 1
- path parser rejects Path defaults HOT 1
- `TypeError: _field2method.<locals>.method()` using `environs[django]` HOT 3
- Variables expanding in dotenv files doesn't respect other sources of Env vars HOT 2
- Bringing environments to subprocess HOT 2
- Default values and subcast
- Is TOML support wanted? HOT 1
- All environment variable names and associated values logged on unhandled env attribute error HOT 3
- errors with raise statements and basestring.... not python3 compatable? HOT 2
- fail if specified .env file does not exist HOT 2
- add "smtp+ssl://, smtp+tls://" supports to email_url HOT 1
- Default values defined in casted types HOT 1
- Inconsistent behavior with `env.list` HOT 1
- Add the ability to create an initial .env file when starting a new project HOT 8
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from environs.