Esempio n. 1
0
class DefaultHandlerTests(unittest.TestCase):
    def setUp(self):
        self.formatter = JsonFormatter()

    def test_it_converts_datetime_objects_to_strings(self):
        obj = datetime(
            year=2006,
            month=6,
            day=6,
            hour=6,
            minute=6,
            second=6,
            microsecond=666666
        )
        result = self.formatter._default_handler(obj)
        # Se o objeto datetime tiver microsecond, `.isoformat()` serializa esse valor
        self.assertEqual(result, '2006-06-06T06:06:06.666666')

    def test_it_converts_exceptions_to_strings(self):
        obj = KeyError("Xablau")
        result = self.formatter._default_handler(obj)
        self.assertEqual(result, "Exception: KeyError('Xablau',)")

    def test_it_calls_callable_objects_and_returns_its_return_value(self):
        obj = lambda: "Xablau"
        result = self.formatter._default_handler(obj)
        self.assertEqual(result, "Xablau")

    def test_it_typecasts_object_to_string_if_type_doesnt_match_anything(self):
        obj = 4.2
        result = self.formatter._default_handler(obj)
        self.assertEqual(result, "4.2")
Esempio n. 2
0
 def setUp(self):
     self.record = LogRecord(
         level=30,
         name='aiologger',
         pathname="/aiologger/tests/formatters/test_json_formatter.py",
         lineno=42,
         msg="Xablau",
         exc_info=None,
         args=None
     )
     self.formatter = JsonFormatter()
Esempio n. 3
0
 def test_json_properly_serialized_when_bytes_object(self):
     self.record.msg = {"dog": "Xablau"}
     custom_formatter = JsonFormatter(serializer=orjson.dumps)
     # Note: json.dumps by default uses this separator (', ', ': ')
     # adding a whitespace whereas with orjson it is not
     # so to have a perfect match is it necessary to specify it
     custom_orjson_serializer_msg = custom_formatter.format(self.record)
     default_json_serializer_msg = self.formatter.serializer(
         {"dog": "Xablau"}, separators=(",", ":"))
     self.assertEqual(custom_orjson_serializer_msg,
                      default_json_serializer_msg)
Esempio n. 4
0
class DefaultHandlerTests(unittest.TestCase):
    def setUp(self):
        self.formatter = JsonFormatter()

    def test_it_converts_datetime_objects_to_strings(self):
        obj = datetime(
            year=2006,
            month=6,
            day=6,
            hour=6,
            minute=6,
            second=6,
            microsecond=666_666,
        )
        result = self.formatter._default_handler(obj)
        # Se o objeto datetime tiver microsecond, `.isoformat()` serializa esse valor
        self.assertEqual(result, "2006-06-06T06:06:06.666666")

    def test_it_converts_exceptions_to_strings(self):
        class MyException(Exception):
            def __repr__(self):
                return "I'm an error"

        obj = MyException("Xablau")
        result = self.formatter._default_handler(obj)
        self.assertEqual(result, "Exception: I'm an error")

    def test_it_calls_callable_objects_and_returns_its_return_value(self):
        obj = CallableWrapper(lambda: "Xablau")
        result = self.formatter._default_handler(obj)
        self.assertEqual(result, "Xablau")

    def test_it_typecasts_object_to_string_if_type_doesnt_match_anything(self):
        obj = 4.2
        result = self.formatter._default_handler(obj)
        self.assertEqual(result, "4.2")

    def test_it_converts_exception_types_to_strings(self):
        class MyException(Exception):
            def __init__(self, errors):
                self.errors = errors

        result = self.formatter._default_handler(MyException)

        self.assertEqual(result, str(MyException))
Esempio n. 5
0
class JsonFormatterTests(unittest.TestCase):
    def setUp(self):
        self.record = LogRecord(
            level=30,
            name='aiologger',
            pathname="/aiologger/tests/formatters/test_json_formatter.py",
            lineno=42,
            msg="Xablau",
            exc_info=None,
            args=None
        )
        self.formatter = JsonFormatter()

    def test_default_fieldname_is_overwriteable(self):
        formatter = JsonFormatter(default_msg_fieldname='dog')

        self.assertEqual(formatter.default_msg_fieldname, 'dog')
        msg = formatter.format(self.record)
        self.assertEqual(msg, formatter.serializer({'dog': 'Xablau'}))

    def test_format_adds_exceptions_infos(self):
        self.record.exc_info = "Xena"
        self.record.exc_text = 'Xablito'

        self.assertEqual(
            self.formatter.format(self.record),
            self.formatter.serializer({
                'msg': 'Xablau',
                'exc_info': 'Xena',
                'exc_text': 'Xablito'
            })
        )

    def test_format_logs_msg_as_is_if_msg_is_a_dict(self):
        self.record.msg = {'dog': 'Xablau'}

        msg = self.formatter.format(self.record)
        self.assertEqual(
            msg,
            self.formatter.serializer({
                'dog': 'Xablau'
            })
        )
Esempio n. 6
0
class JsonFormatterTests(unittest.TestCase):
    def setUp(self):
        self.record = LogRecord(
            level=30,
            name="aiologger",
            pathname="/aiologger/tests/formatters/test_json_formatter.py",
            lineno=42,
            msg="Xablau",
            exc_info=None,
            args=None,
        )
        self.formatter = JsonFormatter()

    def test_default_fieldname_is_overwriteable(self):
        formatter = JsonFormatter(default_msg_fieldname="dog")

        self.assertEqual(formatter.default_msg_fieldname, "dog")
        msg = formatter.format(self.record)
        self.assertEqual(msg, formatter.serializer({"dog": "Xablau"}))

    def test_format_adds_exceptions_infos(self):
        self.record.exc_info = "Xena"
        self.record.exc_text = "Xablito"

        self.assertEqual(
            self.formatter.format(self.record),
            self.formatter.serializer({
                "msg": "Xablau",
                "exc_info": "Xena",
                "exc_text": "Xablito"
            }),
        )

    def test_format_logs_msg_as_is_if_msg_is_a_dict(self):
        self.record.msg = {"dog": "Xablau"}

        msg = self.formatter.format(self.record)
        self.assertEqual(msg, self.formatter.serializer({"dog": "Xablau"}))
Esempio n. 7
0
    async def handle_error(self, record: LogRecord,
                           exception: Exception) -> None:
        """
        Handle errors which occur during an emit() call.

        This method should be called from handlers when an exception is
        encountered during an emit() call. This is what is mostly wanted
        for a logging system - most users will not care about errors in
        the logging system, they are more interested in application errors.
        You could, however, replace this with a custom handler if you wish.
        The record which was being processed is passed in to this method.
        """
        if not settings.HANDLE_ERROR_FALLBACK_ENABLED:
            return

        msg = JsonFormatter.format_error_msg(record, exception)
        json.dump(msg, sys.stderr)
        sys.stderr.write("\n")
Esempio n. 8
0
 def setUp(self):
     self.formatter = JsonFormatter()
Esempio n. 9
0
    def test_default_fieldname_is_overwriteable(self):
        formatter = JsonFormatter(default_msg_fieldname='dog')

        self.assertEqual(formatter.default_msg_fieldname, 'dog')
        msg = formatter.format(self.record)
        self.assertEqual(msg, formatter.serializer({'dog': 'Xablau'}))
Esempio n. 10
0
    def test_default_fieldname_is_overwriteable(self):
        formatter = JsonFormatter(default_msg_fieldname="dog")

        self.assertEqual(formatter.default_msg_fieldname, "dog")
        msg = formatter.format(self.record)
        self.assertEqual(msg, formatter.serializer({"dog": "Xablau"}))
Esempio n. 11
0
class JsonFormatterTests(unittest.TestCase):
    def setUp(self):
        self.record = LogRecord(
            level=30,
            name="aiologger",
            pathname="/aiologger/tests/formatters/test_json_formatter.py",
            lineno=42,
            msg="Xablau",
            exc_info=None,
            func="a_function_name",
            args=None,
        )
        self.formatter = JsonFormatter()

    def test_default_fieldname_is_overwriteable(self):
        formatter = JsonFormatter(default_msg_fieldname="dog")

        self.assertEqual(formatter.default_msg_fieldname, "dog")
        msg = formatter.format(self.record)
        self.assertEqual(msg, formatter.serializer({"dog": "Xablau"}))

    def test_format_adds_exceptions_infos(self):
        self.record.exc_info = "Xena"
        self.record.exc_text = "Xablito"

        self.assertEqual(
            self.formatter.format(self.record),
            self.formatter.serializer({
                "msg": "Xablau",
                "exc_info": "Xena",
                "exc_text": "Xablito"
            }),
        )

    def test_format_logs_msg_as_is_if_msg_is_a_dict(self):
        self.record.msg = {"dog": "Xablau"}

        msg = self.formatter.format(self.record)
        self.assertEqual(msg, self.formatter.serializer({"dog": "Xablau"}))

    @freeze_time("2019-06-01T19:20:13.401262")
    def test_format_error_msg(self):
        try:
            raise OSError("Broken pipe")
        except Exception as e:
            msg = self.formatter.format_error_msg(record=self.record,
                                                  exception=e)
        self.assertEqual(
            msg,
            {
                "record": {
                    "line_number": 42,
                    "level": "WARNING",
                    "file_path": "test_json_formatter.py",
                    "function": "a_function_name",
                    "msg": "Xablau",
                },
                "logged_at": "2019-06-01T19:20:13.401262",
                "logger_exception": {
                    "type": "<class 'OSError'>",
                    "exc": "Broken pipe",
                    "traceback": ANY,
                },
            },
        )

    @freeze_time("2019-06-01T19:20:13.401262")
    def test_format_error_msg_without_traceback(self):
        msg = self.formatter.format_error_msg(record=self.record,
                                              exception=OSError("Broken pipe"))
        self.assertEqual(
            msg,
            {
                "record": {
                    "line_number": 42,
                    "level": "WARNING",
                    "file_path": "test_json_formatter.py",
                    "function": "a_function_name",
                    "msg": "Xablau",
                },
                "logged_at": "2019-06-01T19:20:13.401262",
                "logger_exception": {
                    "type": "<class 'OSError'>",
                    "exc": "Broken pipe",
                    "traceback": ANY,
                },
            },
        )
Esempio n. 12
0
class JsonFormatterTests(unittest.TestCase):
    def setUp(self):
        self.record = LogRecord(
            level=30,
            name="aiologger",
            pathname="/aiologger/tests/formatters/test_json_formatter.py",
            lineno=42,
            msg="Xablau",
            exc_info=None,
            func="a_function_name",
            args=None,
        )
        self.formatter = JsonFormatter()

    def test_default_fieldname_is_overwriteable(self):
        formatter = JsonFormatter(default_msg_fieldname="dog")

        self.assertEqual(formatter.default_msg_fieldname, "dog")
        msg = formatter.format(self.record)
        self.assertEqual(msg, formatter.serializer({"dog": "Xablau"}))

    def test_format_adds_exceptions_infos(self):
        self.record.exc_info = "Xena"
        self.record.exc_text = "Xablito"

        self.assertEqual(
            self.formatter.format(self.record),
            self.formatter.serializer({
                "msg": "Xablau",
                "exc_info": "Xena",
                "exc_text": "Xablito"
            }),
        )

    def test_format_logs_msg_as_is_if_msg_is_a_dict(self):
        self.record.msg = {"dog": "Xablau"}

        msg = self.formatter.format(self.record)
        self.assertEqual(msg, self.formatter.serializer({"dog": "Xablau"}))

    @freeze_time("2019-06-01T19:20:13.401262")
    def test_format_error_msg(self):
        try:
            raise OSError("Broken pipe")
        except Exception as e:
            msg = self.formatter.format_error_msg(record=self.record,
                                                  exception=e)
        self.assertEqual(
            msg,
            {
                "record": {
                    "line_number": 42,
                    "level": "WARNING",
                    "file_path": "test_json_formatter.py",
                    "function": "a_function_name",
                    "msg": "Xablau",
                },
                "logged_at": "2019-06-01T19:20:13.401262",
                "logger_exception": {
                    "type": "<class 'OSError'>",
                    "exc": "Broken pipe",
                    "traceback": ANY,
                },
            },
        )

    @freeze_time("2019-06-01T19:20:13.401262")
    def test_format_error_msg_without_traceback(self):
        msg = self.formatter.format_error_msg(record=self.record,
                                              exception=OSError("Broken pipe"))
        self.assertEqual(
            msg,
            {
                "record": {
                    "line_number": 42,
                    "level": "WARNING",
                    "file_path": "test_json_formatter.py",
                    "function": "a_function_name",
                    "msg": "Xablau",
                },
                "logged_at": "2019-06-01T19:20:13.401262",
                "logger_exception": {
                    "type": "<class 'OSError'>",
                    "exc": "Broken pipe",
                    "traceback": ANY,
                },
            },
        )

    def test_json_properly_serialized_when_bytes_object(self):
        self.record.msg = {"dog": "Xablau"}
        custom_formatter = JsonFormatter(serializer=orjson.dumps)
        # Note: json.dumps by default uses this separator (', ', ': ')
        # adding a whitespace whereas with orjson it is not
        # so to have a perfect match is it necessary to specify it
        custom_orjson_serializer_msg = custom_formatter.format(self.record)
        default_json_serializer_msg = self.formatter.serializer(
            {"dog": "Xablau"}, separators=(",", ":"))
        self.assertEqual(custom_orjson_serializer_msg,
                         default_json_serializer_msg)

    def test_raise_exception_when_serialiazed_result_type_not_valid(self):
        with self.assertRaises(TypeError):

            def _serializer(msg, default, **kwargs):
                data = int(5)
                return data

            self.formatter.serializer = _serializer
            returned_msg = self.formatter.format(self.record)
Esempio n. 13
0
            loop=loop,
            tz=tz,
            formatter=formatter,
        )
        created_logger.append(_logger)
        return _logger

    yield _make_logger

    await created_logger.pop().shutdown()


@pytest.mark.asyncio
@pytest.mark.parametrize("level,formatter", [
    (logging.INFO, None),
    (logging.INFO, JsonFormatter()),
])
async def test_dsjsonlogger(monkeypatch, make_logger, level, formatter):
    virtual_stdout = io.StringIO()
    virtual_stderr = io.StringIO()
    with monkeypatch.context() as monkey:
        monkey.setattr(sys, "stdout", virtual_stdout)
        monkey.setattr(sys, "stderr", virtual_stderr)

        logger = make_logger(
            level=level,
            formatter=formatter,
        )

        await logger.info('abc')