question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Set extra record cause "KeyError" issue in FastAPI

See original GitHub issue

When i set some extra record in fastAPI startup event caused something error

Versions:

  • python 3.8.12
  • loguru 0.6.0
  • fastapi 0.75

Code:

def logger_init():
    logger.remove()
    logger.add(
        sys.stdout,
        format="{extra[event]}",
    )
   context_logger = logger.bind(event="access")
   return context_logger

app = FastAPI()
@app.on_event("startup")
async def startup_event():
    logger = logger_init()
    logger.info("Start up")
       


Error message :

--- Logging error in Loguru Handler #1 ---
Record was: {'elapsed': datetime.timedelta(microseconds=270683), 'exception': None, 'extra': {}, 'file': (name='__init__.py', path='/app/./app/__init__.py'), 'function': 'startup_event', 'level': (name='INFO', no=20, icon='ℹ️'), 'line': 100, 'message': '--- Startup Event ---', 'module': '__init__', 'name': 'app', 'process': (id=229, name='SpawnProcess-102'), 'thread': (id=139944207652672, name='MainThread'), 'time': datetime(2022, 7, 6, 14, 51, 4, 487669, tzinfo=datetime.timezone(datetime.timedelta(0), 'UTC'))}
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/loguru/_handler.py", line 155, in emit
    formatted = precomputed_format.format_map(formatter_record)
KeyError: 'event'
--- End of logging error ---

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:9 (5 by maintainers)

github_iconTop GitHub Comments

3reactions
Delgancommented, Jul 11, 2022

@GGGoingdown Thanks for the fully reproducible example.

The provider value is only present in the logger object returned by .bind(). The extra dict of default logger is empty, which causes a KeyError during formatting. You can set a default value with logger.configure(extra={"provider": None}) for example.

1reaction
Delgancommented, Jul 12, 2022

Use the patch() function then:

logger.patch(lambda record: record.update(event="login")).debug("Example message!")
Read more comments on GitHub >

github_iconTop Results From Across the Web

[BUG] OpenAPI KeyError on body parameter when field types ...
Error Reason: fastapi converts a dataclasses.dataclass into class pydantic.BaseModel model. Thereby, fastapi treats the same dataclass model as ...
Read more >
Handling Errors - FastAPI
When a request contains invalid data, FastAPI internally raises a RequestValidationError . And it also includes a default exception handler for it. To...
Read more >
MemoryError with FastApi and SpaCy - nlp - Stack Overflow
The SpaCy tokenizer seems to cache each token in a map internally. Consequently, each new token increases the size of that map.
Read more >
loguru Documentation - Read the Docs
Loguru helps you identify problems by allowing the entire stack trace to ... your logger messages by modifying the extra record attribute.
Read more >
AWS Lambda function errors in Python
This page describes how to view Lambda function invocation errors for the Python runtime using the Lambda console and the AWS CLI.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found