Skip to content

logger.contextualize and threading #1318

Open
@zmeir

Description

@zmeir

Hi,

First just wanted to say I'm really enjoying this package. It made logging fun and simple for me.

I have a question/issue when trying to log from a thread inside a logger.contextualize scope.

Here's my example:

import sys
import asyncio
import threading
from loguru import logger, _defaults

logger.remove(None)
logger.add(sys.stderr, format=_defaults.LOGURU_FORMAT + " | {extra}")

def thread_func():
    logger.info("hello thread")

async def async_func():
    logger.info("hello async")

async def main():
    with logger.contextualize(a=1):
        await async_func()
        threading.Thread(target=thread_func, daemon=True).start()

asyncio.run(main())

And here's my output:

2025-03-06 09:36:54.691 | INFO     | __main__:async_func:13 - hello async | {'a': 1}
2025-03-06 09:36:54.691 | INFO     | __main__:thread_func:10 - hello thread | {}

As you can see, the context isn't passed to the thread function, only to the async one.

Is there something I'm missing to make the context pass to the thread? Or is this capability not supported?

Version info:

  • OS: macOS 14.7.2 (23H311)
  • Python: 3.12.8
  • Loguru: 0.7.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions