Package: data-annalist
AnnalistAudit trail generator for data processing scripts.Free software: GNU General Public License v3Documentation:https://annalist.readthedocs.io.UsageCreate anAnnalistobject at the base of the module you’d like to audit. use the@Annalist.annalizedecorator on any function you would like to annalizefrom annalist.annalist import Annalist
from annalist.decorators import function_logger

ann = Annalist()
ann.configure()

@function_logger
def example_function():
    ...Annalist also works on class methods, with the help of theClassLoggerdecorator.from annalist.decorators import ClassLogger

class ExampleClass():

    # Initializers can be annalized just fine
    @ClassLogger  # type: ignore
    __init__(self, arg1, arg2):
        self.arg1 = arg1
        self._arg2 = arg2
        ...

    # DO NOT put an annalizer on a property definition.
    # The annalizer calls the property itself, creating infinite recursion.
    @property
    def arg2(self):
        return self._arg2

    # Putting an annalizer on a setter is fine though.
    # Just make sure you put it after the setter decorator.
    @ClassLogger  # type: ignore
    @arg2.setter
    def arg2(self, value):
        self._arg2 = value

    # DO NOT put it on the __repr__ either.
    # Same as before, this creates infinite recursion.
    def __repr__(self):
        return f"{str(arg1)}: {str(arg2)}"In the main script, the Annalist object must be called again. This will point to the singleton object initialized in the dependency. The annalist must be configured before usage.NoteMyPy issuesNote the# type: ignoreinline comments. These are only necessary when usingmypy, which doesn’t really seem to like decorators. They need to be supplied when decorating an__init__constructor method, or when adding multiple decorators to a method.>>> ann = Annalist()
>>> ann.configure(logger_name="Example Logger", analyst_name="Speve")Now the annalized code can be run like normal, and will be audited.>>> example_function()
2023/11/2 09:42:13 | INFO | example_function called by Speve as part of Example Logger sessionFormattersAnnalist is built on the standard pythonlogginglibrary. Formatters can be specified in the same syntax as is documented in thelogging docs. The available fields can be found inFields.Annalist supports two formatters. TheFile formattersformats the output to the logfile, andStream formatterformats the console output.from annalist.annalist import Annalist

ann = Annalist()
ann.configure(...)

ann.set_file_formatter(
    "%(asctime)s, %(analyst_name)s, example_funtion "
    "| %(message)s",
)

ann.set_stream_formatter(
    "%(asctime)s, %(function_name)s "
)In this example, the console output might be>>> example_function()
2023/11/2 09:42:13, example_functionwhereas the contents of the logfile might be:2023/11/2 09:42:13, example_function, Speve | This is an example.FieldsAnnalist collects information about a decorated function and makes those available as fields. Additionally, the fields from the logging library are also available, although they are generally less useful. Below are all the useful features that are available. See all the logging fieldshere.The reason for their limited usefulness are that most of the code references made there point to the annalist library, and not the decorated code.All the fields that we consider useful are listed below:FieldDescriptionSourceanalyst_nameName of the analyst writing the scriptUser configuredfunction_nameFunction NameFunction Inspectionfunction_docFunction DocstringFunction Inspectionret_valReturn valueFunction Inspectionret_val_typeReturn value typeFunction Inspectionret_annotationAnnotation of return valueFunction InspectionparamsInput parametersFunction InspectionasctimeTime of function callLogging LibrarylevelnameLogging level nameLogging LibrarylevelnoLogging level numberLogging Librarymessage*Needs to be passed as extra paramLogging LibrarynameLogger nameLogging LibraryThemessagefield is an optional parameter that can be passed directly to the decorator. This is the simplest way to add more information to a function log.@function_logger(message="this is a message")
def example_function():
    ...You can also specify the level of the logger in the same way, as a decorator keword argument.@function_logger(level="DEBUG")
def example_function():
    ...Unfortunately, Annalist does not yet offer support of passing these fields into the@ClassLogger. However, we can still get information to the logger by inspecting the method arguments, and the attributes on the class instance. Consider the following setup:from annalist.decorators import ClassLogger

class MyClass:
    @ClassLogger  # type: ignore
    def __init__(attr, prop):
        self.attr = attr
        self._prop = prop

    @property
    def prop(self):
        return prop

    @ClassLogger  # type: ignore
    @prop.setter
    def prop(self, value):
        self._prop = value

    @ClassLogger
    def square_attr(self):
        return self.attr ** 2

    @ClassLogger
    def add_prop_to_attr(self):
        return attr + prop

    @ClassLogger  # type: ignore
    @staticmethod
    def increment_value(attr):
        return attr += 1Note the two class attributes namedattrandprop. We can track these properties based on their variable names by passing it into the formatter:>>> from annalist.annalist import Annalist
>>> ann = Annalist()
>>> ann.configure(...)
>>> ann.add_stream_formatter("%(function_name)s | prop: %(prop)s | attr: %(attr)s")TheClassLoggerdecorator activates upon runtime and inspects the namespace. First, it looks for the attribute in the names of the input arguments of the decorated function. If found, it sends it to the formatter (See “Custom Fields”):>>> mc = MyClass(7, 2)
>>> mc.prop = 3
prop | prop: 3 | attr: 7Notice that thesetterofpropcausedClassLoggerto look for the values ofpropandattron themcinstance.>>> mc.square_attr()
49
square_attr | prop: 3 | attr: 7Notice how the functionsquare_attrdid not alter the value ofattr.Because this logger is sensitive to the state of the logger, it is important to be weary of variable names.>>> mc.increment_value(5)
6
square_attr | prop: 3 | attr: 5Notice how, despite having no real reference to the attributeattron the namespace, the logger found the input argument namedattr, and associated this with the attribute it is logging. I believe this to be a useful feature, but care should be taken when using it like this.Custom FieldsAnnalist accepts any number of arbitrary fields in the formatter. If these fields are not one of the fields available by default, the fields is dynamically added and processed. However, this field must then be passed to the decorator in theextra_infoargument.For example, you might set the formatter as follows. In this example, the fieldssiteandhts_fileare custom, and are not available by default.from annalist.annalist import Annalist

ann = Annalist()
ann.configure(...)

ann.set_file_formatter(
    "%(asctime)s, %(analyst_name)s, %(site)s, %(hts_file)s "
    "| %(message)s",
)Then, passing those parameters into the example function looks like this:from annalist.decorators import function_logger
hts_file = "file.hts"

@function_logger(
    level="INFO",
    message="This decorator passes extra parameters",
    extra_info={
        "site_name": "Site one",
        "hts_file": hts_file,
    }
)
def example_function(arg1, arg2):
    ...If the custom fields are not included in a function decorator, they will simply default toNone.Thefunction_loggercan also be used in “wrapper” mode. This is useful when an undecorated function needs to be annalized at call-time:function_logger(
    example_function,
    level="INFO",
    message="This decorator passes extra parameters",
    extra_info={
        "site_name": "Site one",
        "hts_file": hts_file,
    }
)(arg1, arg2)When using Annalist in a class method, you might want to log class attributes. Unfortunately, the following syntax will not work, since the decorator has no knowledge of the class instance (self).class ExampleClass:
    ...

    @function_logger(
        level="INFO",
        message="This decorator passes extra parameters",
        extra_info={
            "site_name": self.site_name, # THIS DOES NOT WORK!
            "hts_file": self.hts_file, # THIS DOES NOT WORK!
        }
    )
    def example_method(self):
        ...The way to track class attributes is to use theClassLoggerdecorator. This decorator activates at runtime. Any custom fields passed to the Annalist formatter are noted, andClassLoggerinspects the class instance for attributes with the same name.from annalist.decorators import ClassLogger

class ExampleClass:
    def __init__(self, attr):
        self.attr = attr

    @ClassLogger
    def example_function(self):
        ...See annalist.decorators.ClassLogger for more details.LevelsAnnalist uses the levels as defined in the logging library. Upon configuration, thedefault levelcan be set, which is the level at which all logs are logged unless overridden. The default value fordefault levelis “INFO”.ann.configure(
    analyst_name="Speve",
    stream_format_str=format_str,
    level_filter="WARNING",
)A annalized method can be logged at a raised or lowered level by specifying the logging level explicitely in the decorator:@function_logger(level="DEBUG")
def untracked_function():
    ...Feature RoadmapThis roadmap outlines the planned features and milestones for the development of our deterministic and reproducible process auditing system.Milestone 1: Audit Logging Frameworkx Develop a custom audit logging framework or class.
x Capture function names, input parameters, return values, data types, and timestamps.
x Implement basic logging mechanisms for integration.Milestone 1.5: Hilltop Auditing Parityx Define custom fields and formatters
x Manage logger levels correctlyMilestone 2: Standardized Logging FormatDefine a standardized logging format for comprehensive auditing.Ensure consistency and machine-readability of the logging format.Milestone 3: Serialization and DeserializationImplement serialization and deserialization mechanisms.Store and retrieve complex data structures and objects.Test serialization for data integrity.Milestone 4: Versioning and Dependency TrackingCapture and log codebase version (Git commit hash) and dependencies.Ensure accurate logging of version and dependency information.Milestone 5: Integration TestingCreate integration tests using the audit logging framework.Log information during the execution of key processes.Begin development of process recreation capability.Milestone 6: Reproduction Tool (Partial)Develop a tool or script to read and reproduce processes from the audit trail.Focus on recreating the environment and loading serialized data.Milestone 7: Documentation (Partial)Create initial documentation.Explain how to use the audit logging framework and the audit trail format.Document basic project functionalities.Milestone 8: Error HandlingImplement robust error handling for auditing and reproduction code.Gracefully handle potential issues.Provide informative and actionable error messages.Milestone 9: MVP TestingConduct testing of the MVP.Reproduce processes from the audit trail and verify correctness.Gather feedback from initial users within the organization.Milestone 10: MVP DeploymentDeploy the MVP within the organization.Make it available to relevant team members.Encourage usage and collect user feedback.Milestone 11: Feedback and IterationGather feedback from MVP users.Identify shortcomings, usability issues, or missing features.Prioritize and plan improvements based on user feedback.Milestone 12: Scaling and ExtendingExplore scaling the solution to cover more processes.Add additional features and capabilities to enhance usability.Please note that milestones may overlap, and the order can be adjusted based on project-specific needs. We aim to remain flexible and responsive to feedback during development.CreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.