Elastic Path Commerce Development

Including audit metadata

Including audit metadata

When Object Auditing is enabled, Commerce Manager passes transaction-related metadata to the persistence layer, such as the Commerce Manager user ID, so that it can be included in the audit records.

To include additional audit metadata, create a method similar to the following and pass in the metadata you wish to store in the persistence layer. The following example does so for the userGuid.

private void storeUserIdForAuditing(final CmUser cmUser) {
   Map<String, String> metadata = ServiceLocator.getService(ContextIdNames.PERSISTENCELISTENER_METADATA_MAP);
   metadata.put(WebConstants.USER_GUID, cmUser.getGuid());     
}
      

Your new userGuid metadata is then passed to the following map obtained from the Spring Context:

<bean id="persistenceListenerMetadataMap" class="com.elasticpath.commons.ThreadLocalMap" scope="singleton" />

Next, override AuditDaoImpl.processMetadata() to handle the extended metadata. The code after the call to super.processMetadata() may be different based on the extended metadata you are handling:

public class ExtAuditDaoImpl extends AudiDaoImpl {
   public void processMetadata(ChangeTransaction csTransaction, Object persistable, Map<String, Object> metadata) {
            
      super.processMetadata(csTransaction, persistable, metadata);
            
      String customAttr= (String)metadata.get("customAttr");
            
      if(customAttr!= null) {
         ChangeTransactionMetadata customMetadata = this.generateMetadata(csTransaction, "customAttr", customAttr);
         this.getPersistenceEngine().save(customMetadata );
      }
            
   }
            
}
      

The ThreadLocalMap class is an implementation of the Map interface that is local to the current thread. It will contain key/value pairs of audit metadata that can be consumed by the auditing listener and stored as part of the audit records.