Skip to content

Commit 65c5b64

Browse files
committed
app-specific logger
1 parent 666285b commit 65c5b64

File tree

6 files changed

+136
-99
lines changed

6 files changed

+136
-99
lines changed

optimade/server/create_app.py

Lines changed: 44 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,12 @@
1212

1313
config_warnings = w
1414

15+
import logging
16+
1517
from optimade import __api_version__, __version__
1618
from optimade.server.entry_collections import EntryCollection, create_entry_collections
1719
from 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
1921
from optimade.server.mappers.entries import BaseResourceMapper
2022
from optimade.server.middleware import OPTIMADE_MIDDLEWARE
2123
from optimade.server.routers import (
@@ -58,13 +60,15 @@ def add_optional_versioned_base_urls(app: FastAPI, index: bool = False):
5860

5961

6062
def 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

130134
def 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

optimade/server/entry_collections/elasticsearch.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,15 @@
1010
from optimade.models import EntryResource
1111
from optimade.server.config import ServerConfig
1212
from optimade.server.entry_collections import EntryCollection, PaginationMechanism
13-
from optimade.server.logger import LOGGER
13+
from optimade.server.logger import get_logger
1414
from optimade.server.mappers import BaseResourceMapper
1515

1616

1717
def get_elastic_client(config: ServerConfig) -> Optional["Elasticsearch"]:
1818
from elasticsearch import Elasticsearch
1919

2020
if config.database_backend.value == "elastic":
21-
LOGGER.info("Using: Elasticsearch backend at %s", config.elastic_hosts)
21+
get_logger().info("Using: Elasticsearch backend at %s", config.elastic_hosts)
2222
return Elasticsearch(hosts=config.elastic_hosts)
2323
return None
2424

@@ -97,7 +97,9 @@ def create_optimade_index(self) -> None:
9797
body["mappings"]["properties"] = properties
9898
self.client.indices.create(index=self.name, ignore=400, **body)
9999

100-
LOGGER.debug(f"Created Elastic index for {self.name!r} with parameters {body}")
100+
get_logger().debug(
101+
f"Created Elastic index for {self.name!r} with parameters {body}"
102+
)
101103

102104
@property
103105
def predefined_index(self) -> dict[str, Any]:

optimade/server/entry_collections/mongo.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from optimade.models import EntryResource
88
from optimade.server.config import ServerConfig, SupportedBackend
99
from optimade.server.entry_collections import EntryCollection
10-
from optimade.server.logger import LOGGER
10+
from optimade.server.logger import get_logger
1111
from optimade.server.mappers import BaseResourceMapper
1212
from optimade.server.query_params import EntryListingQueryParams, SingleEntryQueryParams
1313

@@ -19,10 +19,12 @@ def _close_all_clients(log: bool = True):
1919
try:
2020
client.close()
2121
if log:
22-
LOGGER.debug(f"Closed MongoClient for {backend} {uri}")
22+
get_logger().debug(f"Closed MongoClient for {backend} {uri}")
2323
except Exception as exc:
2424
if log:
25-
LOGGER.warning(f"Failed closing MongoClient {backend} {uri}: {exc}")
25+
get_logger().warning(
26+
f"Failed closing MongoClient {backend} {uri}: {exc}"
27+
)
2628
finally:
2729
_CLIENTS.pop((backend, uri), None)
2830

@@ -42,12 +44,12 @@ def get_mongo_client(config: ServerConfig):
4244
if backend == "mongodb":
4345
from pymongo import MongoClient
4446

45-
LOGGER.info(f"Using: Real MongoDB (pymongo) @ {uri}")
47+
get_logger().info(f"Using: Real MongoDB (pymongo) @ {uri}")
4648
client = MongoClient(uri)
4749
elif backend == "mongomock":
4850
from mongomock import MongoClient
4951

50-
LOGGER.info(f"Using: Mock MongoDB (mongomock) @ {uri}")
52+
get_logger().info(f"Using: Mock MongoDB (mongomock) @ {uri}")
5153
client = MongoClient(uri)
5254
else:
5355
raise ValueError(f"Unsupported backend {backend}")

optimade/server/exception_handlers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
from optimade.exceptions import BadRequest, OptimadeHTTPException
1111
from optimade.models import ErrorResponse, ErrorSource, OptimadeError
12-
from optimade.server.logger import LOGGER
12+
from optimade.server.logger import get_logger
1313
from optimade.server.routers.utils import JSONAPIResponse, meta_values
1414

1515

@@ -38,7 +38,7 @@ def general_exception(
3838
tb = "".join(
3939
traceback.format_exception(type(exc), value=exc, tb=exc.__traceback__)
4040
)
41-
LOGGER.error("Traceback:\n%s", tb)
41+
get_logger().error("Traceback:\n%s", tb)
4242
debug_info[f"_{config.provider.prefix}_traceback"] = tb
4343

4444
try:

0 commit comments

Comments
 (0)