# Internals

You might be interested in the way things work on the inside of Auditlog. This section covers the internal APIs of Auditlog which is very useful when you are looking for more advanced ways to use the application or if you like to contribute to the project.

The documentation below is automatically generated from the source code.

## Models and fields

class auditlog.models.AuditlogHistoryField(pk_indexable=True, delete_related=False, **kwargs)

  A subclass of py:class:django.contrib.contenttypes.fields.GenericRelation that sets some default variables. This makes it easier to access Auditlog’s log entries, for example in templates.

  By default, this field will assume that your primary keys are numeric, simply because this is the most common case. However, if you have a non-integer primary key, you can simply pass `pk_indexable=False` to the constructor, and Auditlog will fall back to using a non-indexed text based field for this model.

  Using this field will not automatically register the model for automatic logging. This is done so you can be more flexible with how you use this field.

  Parameters:

    - pk_indexable (bool) – Whether the primary key for this model is not an `int` or `long`.

    - delete_related (bool) – Delete referenced auditlog entries together with the tracked object. Defaults to False to keep the integrity of the auditlog.

  bulk_related_objects(objs, using='default')

    Return all objects related to `objs` via this `GenericRelation`.

class auditlog.models.LogEntry(id, content_type, object_pk, object_id, object_repr, serialized_data, action, changes_text, changes, actor, cid, remote_addr, remote_port, timestamp, additional_data, actor_email)
  exception DoesNotExist
  exception MultipleObjectsReturned

class auditlog.models.LogEntryManager(*args, **kwargs)

  Custom manager for the `LogEntry` model.

  get_for_model(model)

    Get log entries for all objects of a specified type.

    Parameters:

      model (class) – The model to get log entries for.

    Returns:

      QuerySet of log entries for the given model.

    Return type:

      QuerySet

  get_for_object(instance)

    Get log entries for the specified model instance.

    Parameters:

      instance (Model) – The model instance to get log entries for.

    Returns:

      QuerySet of log entries for the given model instance.

    Return type:

      QuerySet

  get_for_objects(queryset)

    Get log entries for the objects in the specified queryset.

    Parameters:

      queryset (QuerySet) – The queryset to get the log entries for.

    Returns:

      The LogEntry objects for the objects in the given queryset.

    Return type:

      QuerySet

  log_create(instance, force_log: bool = False, **kwargs)

    Helper method to create a new log entry. This method automatically populates some fields when no explicit value is given.

    Parameters:

      - instance (Model) – The model instance to log a change for.

      - force_log (bool) – Create a LogEntry even if no changes exist.

      - kwargs – Field overrides for the `LogEntry` object.

    Returns:

      The new log entry or None if there were no changes.

    Return type:

      LogEntry

  log_m2m_changes(changed_queryset, instance, operation, field_name, **kwargs)

    Create a new “changed” log entry from m2m record.

    Parameters:

      - changed_queryset (QuerySet) – The added or removed related objects.

      - instance (Model) – The model instance to log a change for.

      - operation – “add” or “delete”.

      - field_name (str) – The name of the changed m2m field.

      - kwargs – Field overrides for the `LogEntry` object.

    Returns:

      The new log entry or None if there were no changes.

    Return type:

      LogEntry

## Middleware

class auditlog.middleware.AuditlogMiddleware(get_response=None)

  Middleware to couple the request’s user to log items. This is accomplished by currying the signal receiver with the user from the request (or None if the user is not authenticated).

## Correlation ID

auditlog.cid.get_cid() → str | None

  Calls the cid getter function based on settings.AUDITLOG_CID_GETTER

  If the setting value is:

  - None: then it calls the default getter (which retrieves the value set in set_cid)

  - callable: then it calls the function

  - type(str): then it imports the function and then call it

  The result is then returned to the caller.

  If your custom getter does not depend on set_header(), then we recommend setting settings.AUDITLOG_CID_GETTER to None.

  Returns:

    The correlation ID

auditlog.cid.set_cid(request: HttpRequest | None = None) → None

  A function to read the cid from a request. If the header is not in the request, then we set it to None.

  Note: we look for the value of AUDITLOG_CID_HEADER in request.headers and in request.META.

  This function doesn’t do anything if the user is supplying their own AUDITLOG_CID_GETTER.

  Parameters:

    request – The request to get the cid from.

  Returns:

    None

## Signal receivers

auditlog.receivers.check_disable(signal_handler)

  Decorator that passes along disabled in kwargs if any of the following is true: - ‘auditlog_disabled’ from threadlocal is true - raw = True and AUDITLOG_DISABLE_ON_RAW_SAVE is True

auditlog.receivers.log_access(sender, instance, **kwargs)

  Signal receiver that creates a log entry when a model instance is accessed in a AccessLogDetailView.

  Direct use is discouraged, connect your model through `auditlog.registry.register()` instead.

auditlog.receivers.log_create(sender, instance, created, **kwargs)

  Signal receiver that creates a log entry when a model instance is first saved to the database.

  Direct use is discouraged, connect your model through `auditlog.registry.register()` instead.

auditlog.receivers.log_delete(sender, instance, **kwargs)

  Signal receiver that creates a log entry when a model instance is deleted from the database.

  Direct use is discouraged, connect your model through `auditlog.registry.register()` instead.

auditlog.receivers.log_update(sender, instance, **kwargs)

  Signal receiver that creates a log entry when a model instance is changed and saved to the database.

  Direct use is discouraged, connect your model through `auditlog.registry.register()` instead.

auditlog.receivers.make_log_m2m_changes(field_name)

  Return a handler for m2m_changed with field_name enclosed.

## Custom Signals

Django Auditlog provides two custom signals that will hook in before and after any Auditlog record is written from a `create`, `update`, `delete`, or `accessed` action on an audited model.

auditlog.signals.pre_log = <django.dispatch.dispatcher.Signal object>

  Whenever an audit log entry is written, this signal is sent before writing the log. Keyword arguments sent with this signal:

  Parameters:

    - sender (class) – The model class that’s being audited.

    - instance (Any) – The actual instance that’s being audited.

    - action (Action) – The action on the model resulting in an audit log entry. Type: `auditlog.models.LogEntry.Action`

  The receivers’ return values are sent to any `post_log()` signal receivers, with one exception: if any receiver returns False, no logging will be made. This can be useful if logging should be conditionally enabled / disabled

auditlog.signals.post_log = <django.dispatch.dispatcher.Signal object>

  Whenever an audit log entry is written, this signal is sent after writing the log. This signal is also fired when there is an error in creating the log.

  Keyword arguments sent with this signal:

  Parameters:

    - sender (class) – The model class that’s being audited.

    - instance (Any) – The actual instance that’s being audited.

    - action (Action) – The action on the model resulting in an audit log entry. Type: `auditlog.models.LogEntry.Action`

    - changes (Optional[dict]) – The changes that were logged. If there was en error while determining the changes, this will be None. In some cases, such as when logging access to the instance, the changes will be an empty dict.

    - log_entry (Optional[LogEntry]) – The log entry that was created and stored in the database. If there was an error, this will be None.

    - log_created (bool) – Was the log actually created? This could be false if there was an error in creating the log.

    - error (Optional[Exception]) – The error, if one occurred while saving the audit log entry. `None`, otherwise

    - pre_log_results (List[Tuple[method,Any]]) – List of tuple pairs `[(pre_log_receiver, pre_log_response)]`, where `pre_log_receiver` is the receiver method, and `pre_log_response` is the corresponding response of that method. If there are no `pre_log` receivers, then the list will be empty. `pre_log_receiver` is guaranteed to be non-null, but `pre_log_response` may be `None`. This depends on the corresponding `pre_log_receiver`’s return value.

Added in version 3.0.0.

## Calculating changes

auditlog.diff.get_field_value(obj, field, use_json_for_changes=False)

  Gets the value of a given model instance field.

  Parameters:

    - obj (Model) – The model instance.

    - field (Any) – The field you want to find the value of.

  Returns:

    The value of the field as a string.

  Return type:

    str

auditlog.diff.get_fields_in_model(instance)

  Returns the list of fields in the given model instance. Checks whether to use the official _meta API or use the raw data. This method excludes many to many fields.

  Parameters:

    instance (Model) – The model instance to get the fields for

  Returns:

    The list of fields for the given model (instance)

  Return type:

    list

auditlog.diff.get_mask_function(mask_callable: str | None = None) → Callable[[str], str]

  Get the masking function to use based on the following priority: 1. Model-specific mask_callable if provided 2. mask_callable from settings if configured 3. Default mask_str function

  Parameters:

    mask_callable (str) – The dotted path to a callable that will be used for masking.

  Returns:

    A callable that takes a string and returns a masked version.

  Return type:

    Callable[[str], str]

auditlog.diff.is_primitive(obj) → bool

  Checks if the given object is a primitive Python type that can be safely serialized to JSON.

  Parameters:

    obj – The object to check

  Returns:

    True if the object is a primitive type, False otherwise

  Return type:

    bool

auditlog.diff.mask_str(value: str) → str

  Masks the first half of the input string to remove sensitive data.

  Parameters:

    value (str) – The value to mask.

  Returns:

    The masked version of the string.

  Return type:

    str

auditlog.diff.model_instance_diff(old: Model | None, new: Model | None, fields_to_check=None, use_json_for_changes=False)

  Calculates the differences between two model instances. One of the instances may be `None` (i.e., a newly created model or deleted model). This will cause all fields with a value to have changed (from `None`).

  Parameters:

    - old (Model) – The old state of the model instance.

    - new (Model) – The new state of the model instance.

    - fields_to_check (Iterable) – An iterable of the field names to restrict the diff to, while ignoring the rest of the model’s fields. This is used to pass the update_fields kwarg from the model’s save method.

    - use_json_for_changes – whether or not to use a JSON for changes (see settings.AUDITLOG_STORE_JSON_CHANGES)

  Returns:

    A dictionary with the names of the changed fields as keys and a two tuple of the old and new field values as value.

  Return type:

    dict

auditlog.diff.track_field(field)

  Returns whether the given field should be tracked by Auditlog.

  Untracked fields are many-to-many relations and relations to the Auditlog LogEntry model.

  Parameters:

    field (Field) – The field to check.

  Returns:

    Whether the given field should be tracked.

  Return type:

    bool

## Registry

exception auditlog.registry.AuditLogRegistrationError

class auditlog.registry.AuditlogModelRegistry(create: bool = True, update: bool = True, delete: bool = True, access: bool = True, m2m: bool = True, custom: dict[ModelSignal, Callable] | None = None)

  A registry that keeps track of the models that use Auditlog to track changes.

  contains(model: ModelBase) → bool

    Check if a model is registered with auditlog.

    Parameters:

      model – The model to check.

    Returns:

      Whether the model has been registered.

    Return type:

      bool

  register(model: ModelBase = None, include_fields: list[str] | None = None, exclude_fields: list[str] | None = None, mapping_fields: dict[str, str] | None = None, mask_fields: list[str] | None = None, mask_callable: str | None = None, m2m_fields: Collection[str] | None = None, serialize_data: bool = False, serialize_kwargs: dict[str, Any] | None = None, serialize_auditlog_fields_only: bool = False)

    Register a model with auditlog. Auditlog will then track mutations on this model’s instances.

    Parameters:

      - model – The model to register.

      - include_fields – The fields to include. Implicitly excludes all other fields.

      - exclude_fields – The fields to exclude. Overrides the fields to include.

      - mapping_fields – Mapping from field names to strings in diff.

      - mask_fields – The fields to mask for sensitive info.

      - mask_callable – The dotted path to a callable that will be used for masking. If not provided, the default mask_callable will be used.

      - m2m_fields – The fields to handle as many to many.

      - serialize_data – Option to include a dictionary of the objects state in the auditlog.

      - serialize_kwargs – Optional kwargs to pass to Django serializer

      - serialize_auditlog_fields_only – Only fields being considered in changes will be serialized.

  register_from_settings()

    Register models from settings variables

  unregister(model: ModelBase) → None

    Unregister a model with auditlog. This will not affect the database.

    Parameters:

      model – The model to unregister.