Pages

Friday, October 14, 2011

SPAudit: How to write to the audit log

As part of my series on SharePoint auditing, I will demonstrate how to write to the audit log. I will also make a few suggestions for what you can use custom auditing for.

The auditing is centered around the SPAudit class, which is available in all versions of SharePoint 2007 and SharePoint 2010, except in sandboxed solutions.

How do you write to the audit log?

Writing to the audit log is quite easy. All you have to do is add the following line (in this case creating an Update entry):

audit.WriteAuditEvent(
  SPAuditEventType.Update,
  myEventSource,
  myEventData);

Or, if you want to add a custom event - which would probably be the typical case:

audit.WriteAuditEvent(
  myEventName,
  myEventSource,
  myEventData);

This last overload results in an audit log entry of event type SPAuditEventType.Custom, and with event name myEventName.

The event data can be any string value you choose. When writing standard events SharePoint uses XML to describe the event. If you choose to do likewise, it will be a good idea to use some of the same tags that SharePoint employs, such as groupid (a group ID) and user (a user ID). This will make it easier for you if you want to later display the event data in a readable fashion.

What can you use the audit log for?

There are several uses for the audit log:

  • You can record events in your custom solutions. Later, you can retrieve these events for additional processing. For example, you might have a list of products, the price of which are to be updated in a BI database at regular intervals. An event handler on the list registers changes in prices in the audit log, while ignoring other changes to the products. Then, once a week, a timerjob retrieves these event from the audit log, and updates the prices for the selected products in the BI database.
  • As a variation of this, you can use the audit log for error logging. Instead of writing to the ULS log - which only records the error on the local server - you can write to the audit log, and display errors farm-wide on an application page.
  • You can use the audit log as an alternative to the workflow history list. SharePoint by default removes entries from these lists when they are 6 month old, which could cause a loss of important data.

Try it youself

If you have read my other auditing posts How to turn auditing on programmatically and How to write to the audit log there should be nothing stopping you from starting using the SharePoint audit log already today. Have fun.

1 comment:

  1. Hey Thomas

    You mentioned you you can write to the audit log, and display errors farm-wide on an application page.

    How can I capture farm wide activities like feature activated, site collection deleted or created, etc ?

    Appreciate your quick response.

    Thanks
    Jim

    ReplyDelete