diff --git a/README.md b/README.md index 1b4f33c..a931a37 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,32 @@ For example: ``` logger.info('Warning', extra={'extra_key':'extra_value'}) ``` +#### Dynamic Extra Fields +The following additional code example offers the same functionlites that availavle with the extra parameter to add additional fields to logs. The difference is that it uses logging filters so it will add the fields that are declared key-values from the extra dictionary to every log that's generated after adding the fliter. You can keep updating the logs with additional filters. +``` +class ExtraFieldsLogFilter(logging.Filter): + + def __init__(self, extra: dict, *args, **kwargs): + super().__init__(*args, **kwargs) + self.extra = extra + + def filter(self, record): + record.__dict__.update(self.extra) + return True + +def main(): + logger.info("Test log") # Outputs: {"message":"Test log"} + + extra_fields = {"foo":"bar","counter":1} + logger.addFilter(ExtraFieldsLogFilter(extra_fields)) + logger.warning("Warning test log") # Outputs: {"message":"Warning test log","foo":"bar","counter":1} + + error_fields = {"err_msg":"Failed to run due to exception.","status_code":500} + logger.addFilter(ExtraFieldsLogFilter(error_fields)) + logger.error("Error test log") # Outputs: {"message":"Error test log","foo":"bar","counter":1,"err_msg":"Failed to run due to exception.","status_code":500} + +``` ## Django configuration ``` diff --git a/tox.ini b/tox.ini index 7335ca1..bf349a1 100644 --- a/tox.ini +++ b/tox.ini @@ -1,6 +1,6 @@ [tox] minversion = 1.7.2 -envlist = flake8, py3flake8, python3.5, python3.6, python3.7, python3.8, python3.8, pypy, pypy3 +envlist = flake8, py3flake8, python3.5, python3.6, python3.7, python3.8, python3.9, python3.10, python3.11, pypy, pypy3 skip_missing_interpreters = true [testenv]