1212
1313 config_warnings = w
1414
15+ import logging
16+
1517from optimade import __api_version__ , __version__
1618from optimade .server .entry_collections import EntryCollection , create_entry_collections
1719from optimade .server .exception_handlers import OPTIMADE_EXCEPTIONS
18- from optimade .server .logger import LOGGER
20+ from optimade .server .logger import create_logger , set_logging_context
1921from optimade .server .mappers .entries import BaseResourceMapper
2022from optimade .server .middleware import OPTIMADE_MIDDLEWARE
2123from optimade .server .routers import (
@@ -58,13 +60,15 @@ def add_optional_versioned_base_urls(app: FastAPI, index: bool = False):
5860
5961
6062def insert_main_data (
61- config : ServerConfig , entry_collections : dict [str , EntryCollection ]
63+ config : ServerConfig ,
64+ entry_collections : dict [str , EntryCollection ],
65+ logger : logging .Logger ,
6266):
6367 from optimade .utils import insert_from_jsonl
6468
6569 for coll_type in ["links" , "structures" , "references" ]:
6670 if len (entry_collections [coll_type ]) > 0 :
67- LOGGER .info ("Skipping data insert: data already present." )
71+ logger .info ("Skipping data insert: data already present." )
6872 return
6973
7074 def _insert_test_data (endpoint : str | None = None ):
@@ -75,14 +79,14 @@ def _insert_test_data(endpoint: str | None = None):
7579 from optimade .server .routers .utils import get_providers
7680
7781 def load_entries (endpoint_name : str , endpoint_collection : EntryCollection ):
78- LOGGER .debug ("Loading test %s..." , endpoint_name )
82+ logger .debug ("Loading test %s..." , endpoint_name )
7983
8084 endpoint_collection .insert (getattr (data , endpoint_name , []))
8185 if (
8286 config .database_backend .value in ("mongomock" , "mongodb" )
8387 and endpoint_name == "links"
8488 ):
85- LOGGER .debug (
89+ logger .debug (
8690 "Adding Materials-Consortia providers to links from optimade.org"
8791 )
8892 providers = get_providers (add_mongo_id = True )
@@ -92,7 +96,7 @@ def load_entries(endpoint_name: str, endpoint_collection: EntryCollection):
9296 replacement = bson .json_util .loads (bson .json_util .dumps (doc )),
9397 upsert = True ,
9498 )
95- LOGGER .debug ("Done inserting test %s!" , endpoint_name )
99+ logger .debug ("Done inserting test %s!" , endpoint_name )
96100
97101 if endpoint :
98102 load_entries (endpoint , entry_collections [endpoint ])
@@ -102,7 +106,7 @@ def load_entries(endpoint_name: str, endpoint_collection: EntryCollection):
102106
103107 if config .insert_from_jsonl :
104108 jsonl_path = Path (config .insert_from_jsonl )
105- LOGGER .debug ("Inserting data from JSONL file: %s" , jsonl_path )
109+ logger .debug ("Inserting data from JSONL file: %s" , jsonl_path )
106110 if not jsonl_path .exists ():
107111 raise RuntimeError (
108112 f"Requested JSONL file does not exist: { jsonl_path } . Please specify an absolute group."
@@ -114,21 +118,23 @@ def load_entries(endpoint_name: str, endpoint_collection: EntryCollection):
114118 create_default_index = config .create_default_index ,
115119 )
116120
117- LOGGER .debug ("Inserted data from JSONL file: %s" , jsonl_path )
121+ logger .debug ("Inserted data from JSONL file: %s" , jsonl_path )
118122 if config .insert_test_data :
119123 _insert_test_data ("links" )
120124 elif config .insert_test_data :
121125 _insert_test_data ()
122126
123127 if config .exit_after_insert :
124- LOGGER .info ("Exiting after inserting test data." )
128+ logger .info ("Exiting after inserting test data." )
125129 import sys
126130
127131 sys .exit (0 )
128132
129133
130134def insert_index_data (
131- config : ServerConfig , entry_collections : dict [str , EntryCollection ]
135+ config : ServerConfig ,
136+ entry_collections : dict [str , EntryCollection ],
137+ logger : logging .Logger ,
132138):
133139 import bson .json_util
134140 from bson .objectid import ObjectId
@@ -138,10 +144,10 @@ def insert_index_data(
138144 links_coll = entry_collections ["links" ]
139145
140146 if len (links_coll ) > 0 :
141- LOGGER .info ("Skipping index links insert: links collection already populated." )
147+ logger .info ("Skipping index links insert: links collection already populated." )
142148 return
143149
144- LOGGER .debug ("Loading index links..." )
150+ logger .debug ("Loading index links..." )
145151 with open (config .index_links_path ) as f :
146152 data = json .load (f )
147153
@@ -150,14 +156,14 @@ def insert_index_data(
150156 db ["_id" ] = {"$oid" : mongo_id_for_database (db ["id" ], db ["type" ])}
151157 processed .append (db )
152158
153- LOGGER .debug (
159+ logger .debug (
154160 "Inserting index links into collection from %s..." , config .index_links_path
155161 )
156162
157163 links_coll .insert (bson .json_util .loads (bson .json_util .dumps (processed )))
158164
159165 if config .database_backend .value in ("mongodb" , "mongomock" ):
160- LOGGER .debug (
166+ logger .debug (
161167 "Adding Materials-Consortia providers to links from optimade.org..."
162168 )
163169 providers = get_providers (add_mongo_id = True )
@@ -168,31 +174,38 @@ def insert_index_data(
168174 upsert = True ,
169175 )
170176
171- LOGGER .debug ("Done inserting index links!" )
177+ logger .debug ("Done inserting index links!" )
172178
173179 else :
174- LOGGER .warning (
180+ logger .warning (
175181 "Not inserting test data for index meta-database for backend %s" ,
176182 config .database_backend .value ,
177183 )
178184
179185
180- def create_app (config : ServerConfig | None = None , index : bool = False ) -> FastAPI :
186+ def create_app (
187+ config : ServerConfig | None = None ,
188+ index : bool = False ,
189+ logger_tag : str | None = None ,
190+ ) -> FastAPI :
191+ # create app-specific logger
192+ logger = create_logger (logger_tag , config )
193+
181194 if config_warnings :
182- LOGGER .warning (
195+ logger .warning (
183196 f"Invalid config file or no config file provided, running server with default settings. Errors: "
184197 f"{ [warnings .formatwarning (w .message , w .category , w .filename , w .lineno , '' ) for w in config_warnings ]} "
185198 )
186199 else :
187- LOGGER .info (
188- f"Loaded settings from { os .getenv ('OPTIMADE_CONFIG_FILE' , DEFAULT_CONFIG_FILE_PATH )} . "
200+ logger .info (
201+ f"Loaded settings from { os .getenv ('OPTIMADE_CONFIG_FILE' , DEFAULT_CONFIG_FILE_PATH )} "
189202 )
190203
191204 if config is None :
192205 config = ServerConfig ()
193206
194207 if config .debug : # pragma: no cover
195- LOGGER .info ("DEBUG MODE" )
208+ logger .info ("DEBUG MODE" )
196209
197210 title = "OPTIMADE API" if not index else "OPTIMADE API - Index meta-database"
198211 description = """The [Open Databases Integration for Materials Design (OPTIMADE) consortium](https://www.optimade.org/) aims to make materials databases interoperational by developing a common REST API.\n """
@@ -227,12 +240,19 @@ def create_app(config: ServerConfig | None = None, index: bool = False) -> FastA
227240
228241 if not index :
229242 if config .insert_test_data or config .insert_from_jsonl :
230- insert_main_data (config , entry_collections )
243+ insert_main_data (config , entry_collections , logger )
231244 else :
232245 if config .insert_test_data and config .index_links_path .exists ():
233- insert_index_data (config , entry_collections )
246+ insert_index_data (config , entry_collections , logger )
247+
248+ # Add middleware to set logging context
249+ @app .middleware ("http" )
250+ async def set_context (request , call_next ):
251+ set_logging_context (logger_tag )
252+ response = await call_next (request )
253+ return response
234254
235- # Add CORS middleware first
255+ # Add CORS middleware
236256 app .add_middleware (CORSMiddleware , allow_origins = ["*" ])
237257
238258 # Then add required OPTIMADE middleware
0 commit comments