As part of my series on SharePoint auditing, I will demonstrate how to enable auditing programmatically. I will also point out a single dragon lurking in the background.
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 turn the auditing on?When we turn auditing on, what we are really doing is enabling some event handlers in SharePoint. Some of these events we can already catch using SharePoint event receivers, others can not be caught that way. But the core functionality of having an audit log, and being able to CRUD it (well, CRD, since we can Create, Read and Delete, but not Update) is always available.
To turn on auditing you would use the following code, adding whatever flags you need:
This of course removes whatever audit settings there were on the site collection previously. If you want to just ensure that some specific audit types are turned on, then use:
Not only the site collection has audit settings. A SPAudit instance is available from instances of the following classes: SPSite, SPWeb, SPList, SPFolder and SPListItem.
Here be dragons...
If you turn on the auditing for all events, then beware: Your content database will swell with audit data. This is particularly true if you use SPAuditMaskType.View. Subhajit Chatterjee has a post about the problem. Basically, his advise is to have a plan for archiving the audit data somewhere else.
The Masked SharePointer describes a timerjob for cleaning up the audit log periodically.
Try it youself
If you have read my other auditing posts How to write to the audit log and How to read from the audit log there should be nothing stopping you from starting using the SharePoint audit log already today. Have fun.