Search code examples
pythonasynchronousloggingspdlog

Why spdlog not print in async function


import asyncio
from pathlib import Path
import spdlog as spd
import asyncio
import logging

async def A():
    asyncio.create_task(B())
    while True:
        await asyncio.sleep(1)

async def B():
    logger = spd.DailyLogger(name = 'B', filename = 'B.log', hour = 0, minute = 0, async_mode=True)
    logger.set_level(spd.LogLevel.INFO)
    # logging.basicConfig(level=logging.INFO, filename='B.log', filemode='w')
    # logger = logging.getLogger('B')
    while True:
        logger.info('B')
        await asyncio.sleep(1)


if __name__ == "__main__":
    asyncio.run(A())

First, I created a task B inside A, which prints a line of B every second. When I used Python's default logging, everything worked fine, but with C++'s spdlog, there’s no output, regardless of whether I enable async_mode or not.

I have tried to disable async_mode, still the same


Solution

  • By default spdlog doesn't flush for INFO messages, which is why you don't see anything. It will either flush when it gets enough messages (run your program for a long time or change the sleep interval to 0.01 to see that effect), or periodically (though the Python wrapper for spdlog doesn't seem to support changing this setting), or if you change the setting after which types of messages it should flush:

    logger.flush_on(spd.LogLevel.INFO)
    

    (Directly after the .set_level() call.)