1+ import logging
12import os
23from enum import Enum
4+ from typing import Self
35
4- from pydantic import SecretStr , computed_field
6+ from pydantic import SecretStr , computed_field , field_validator , model_validator
57from pydantic_settings import BaseSettings , SettingsConfigDict
68
9+ logger = logging .getLogger (__name__ )
10+
711
812class AppSettings (BaseSettings ):
913 APP_NAME : str = "FastAPI app"
@@ -24,7 +28,7 @@ class LogLevelOption(str, Enum):
2428class LoggingSettings (BaseSettings ):
2529 LOG_LEVEL : LogLevelOption = LogLevelOption .INFO
2630 LOG_FORMAT_AS_JSON : bool = False
27- LOG_TO_FILE : bool = True
31+ LOG_TO_FILE : bool = False
2832
2933
3034class CryptSettings (BaseSettings ):
@@ -147,14 +151,19 @@ class CRUDAdminSettings(BaseSettings):
147151
148152
149153class EnvironmentOption (str , Enum ):
150- LOCAL = "local "
151- STAGING = "staging "
152- PRODUCTION = "production "
154+ LOCAL = "LOCAL "
155+ STAGING = "STAGING "
156+ PRODUCTION = "PRODUCTION "
153157
154158
155159class EnvironmentSettings (BaseSettings ):
156160 ENVIRONMENT : EnvironmentOption = EnvironmentOption .LOCAL
157161
162+ @field_validator ("ENVIRONMENT" , mode = "before" )
163+ @classmethod
164+ def normalize_environment (cls , v : str ) -> str :
165+ return v .upper ()
166+
158167
159168class CORSSettings (BaseSettings ):
160169 CORS_ORIGINS : list [str ] = ["*" ]
@@ -186,5 +195,26 @@ class Settings(
186195 extra = "ignore" ,
187196 )
188197
198+ @model_validator (mode = "after" )
199+ def validate_environment_settings (self ) -> Self :
200+ """The validation should not modify any of the settings.
201+
202+ It should provide feedback to the user if any misconfiguration is detected.
203+ """
204+ environment = self .ENVIRONMENT .value
205+ if environment == EnvironmentOption .PRODUCTION :
206+ if self .LOG_LEVEL == LogLevelOption .DEBUG :
207+ logger .warning (
208+ f"In a { environment } environment, it's recommended to set LOG_LEVEL to INFO, WARNING, or ERROR. "
209+ "It is currently being set to DEBUG."
210+ )
211+ if self .LOG_FORMAT_AS_JSON is False :
212+ logger .warning (
213+ f"In a { environment } environment, it's recommended to set LOG_FORMAT_AS_JSON to true "
214+ "if you are using log aggregation tools."
215+ )
216+
217+ return self
218+
189219
190220settings = Settings ()
0 commit comments