User Tools

Site Tools


notes:sharepoint2010:spaudit

Audit in SharePoint

Retrieve audit records:

// Input params:
// - listId (Guid)
// - listItemId (int)
 
string siteUrl = SPContext.Current.Site.Url;
Guid webId = SPContext.Current.Web.ID;
 
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(siteUrl))
    {
        using (SPWeb web = site.OpenWeb(webId))
        {
            // Get the list.
            SPListCollection lists = web.Lists;
            lists.ListsForCurrentUser = false; // return all lists
            SPList list = lists.GetList(listId, false);
 
            // Get the audit log.
            SPAudit auditLog;
            if (listItemId > 0)
            {
                SPListItem listItem = list.GetItemById(listItemId);
                auditLog = listItem.Audit;
            }
            else
            {
                auditLog = list.Audit;
            }
            SPAuditEntryCollection auditEntries = auditLog.GetEntries();
 
            // Get the user collection.
            SPUserCollection users = site.RootWeb.AllUsers;
 
            var auditItems = (
                from SPAuditEntry item in auditEntries
                from SPUser user in users
                where item.UserId < 999999
                orderby item.Occurred descending
                select new
                {
                    User = users.Cast<SPUser>()
                        .Where(u => u.ID == item.UserId).FirstOrDefault().Name,
                    Occured = 
            SPContext.Current.Site.RootWeb.RegionalSettings.TimeZone.UTCToLocalTime(item.Occurred).ToString(),
                    Event = item.Event.ToString() + " " + item.ItemType.ToString(),
                    Details = item.DocLocation
                }).Distinct();
        }
    }
});
notes/sharepoint2010/spaudit.txt · Last modified: 2016/09/26 by admin