Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

aiologger closes sys.stdout #4

Open
mbrancato opened this issue Jul 14, 2021 · 3 comments
Open

aiologger closes sys.stdout #4

mbrancato opened this issue Jul 14, 2021 · 3 comments

Comments

@mbrancato
Copy link

Why does aiologger close sys.stdout or any handler it doesn't open()?

import asyncio
import aiologger


async def testaiolog():
    logger = aiologger.Logger.with_default_handlers(name="my-logger")
    await logger.info("foo")


print("works")
asyncio.run(testaiolog())
print("doesn't work")

results in:

Traceback (most recent call last):
  File "/Users/mike/Documents/.../aiologgertest.py", line 12, in <module>
    print("doesn't work")
ValueError: I/O operation on closed file.
works
foo
@louis030195
Copy link

Why does aiologger close sys.stdout or any handler it doesn't open()?

import asyncio
import aiologger


async def testaiolog():
    logger = aiologger.Logger.with_default_handlers(name="my-logger")
    await logger.info("foo")


print("works")
asyncio.run(testaiolog())
print("doesn't work")

results in:

Traceback (most recent call last):
  File "/Users/mike/Documents/.../aiologgertest.py", line 12, in <module>
    print("doesn't work")
ValueError: I/O operation on closed file.
works
foo

Any chance you found a solution?

@nikita-krokosh
Copy link

Any updates on this issue?

@adalundhe
Copy link

adalundhe commented Dec 11, 2022

Hello there! I think I've got a semi-reasonable workaround for anyone that's curious. Rather than directly passing sys.stdout or sys.stderr, we create a dup of either and pass that. Example below:

import os
import sys
from aiologger.handlers.streams import AsyncStreamHandler

AsyncStreamHandler(
    stream=os.fdopen(
        os.dup(sys.__stdout__.fileno())
))

Full credit to this StackOverflow answer for the idea: https://stackoverflow.com/a/40845164. Hope this helps!

Quick Edit: This workaround assumes you won't be attempting to re-use the same instance of the Hander/Logger later. I'd recommend creating a logger factory if you plan on passing the same logger between different calls to asyncio.run()/etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants