Integrating with built in logging module - RobertoPrevato/rolog GitHub Wiki

Although rolog is providing interfaces and methods to log in asynchronous way, it can be integrated with existing solutions using synchronous code, if desired. It can be used, for example, to log certain messages to file system using the built-in logging module, while also integrating with external web api such as Azure Application Insights REST api or Datadog, to log certain records using asyncio.

This example shows how to use rolog together with logging module, to configure a log target that writes records to a file on file system.

import asyncio
import logging
from rolog import LogLevel, LoggerFactory, LogRecord
from rolog.targets import DynamicBuiltInLoggingTarget


def get_builtin_sync_logger(name):
    sync_logger = logging.getLogger(name)
    sync_logger.setLevel(logging.DEBUG)
    fh = logging.FileHandler(name + '.log')
    fh.setLevel(logging.DEBUG)
    sync_logger.addHandler(fh)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    return sync_logger


async def example():
    name = __name__
    get_builtin_sync_logger(name)

    factory = LoggerFactory()
    factory.add_target(DynamicBuiltInLoggingTarget())
    logger = factory.get_logger(name)

    await logger.info('Lorem ipsum dolor sit amet')

    try:
        1 / 0
    except Exception as ex:
        await logger.exception('Oh, no!')

    with open(name + '.log', mode='rt', encoding='utf8') as file_log:
        content = file_log.read()

        assert 'Lorem ipsum dolor sit amet' in content
        assert 'ZeroDivisionError: division by zero' in content


loop = asyncio.get_event_loop()
loop.run_until_complete(example())

An example of log output produced by code above is:

2018-10-21 00:21:07,648 - __main__ - INFO - Lorem ipsum dolor sit amet
2018-10-21 00:21:07,648 - __main__ - ERROR - Oh, no!
Traceback (most recent call last):
  File "rologtest2.py", line 28, in example
    1 / 0
ZeroDivisionError: division by zero