第一步 建立SQL Server 数据表
Code
CREATE TABLE [ss_WebEvents] (
[EventId] [char] (32) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[EventTimeUtc] [datetime] NOT NULL ,
[EventTime] [datetime] NOT NULL ,
[EventType] [nvarchar] (256) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[EventSequence] [decimal](19, 0) NOT NULL ,
[EventOccurrence] [decimal](19, 0) NOT NULL ,
[EventCode] [int] NOT NULL ,
[EventDetailCode] [int] NOT NULL ,
[Message] [nvarchar] (1024) COLLATE Chinese_PRC_CI_AS NULL ,
[ApplicationPath] [nvarchar] (256) COLLATE Chinese_PRC_CI_AS NULL ,
[ApplicationVirtualPath] [nvarchar] (256) COLLATE Chinese_PRC_CI_AS NULL ,
[MachineName] [nvarchar] (256) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[RequestUrl] [nvarchar] (1024) COLLATE Chinese_PRC_CI_AS NULL ,
[UserName] [nvarchar] (256) COLLATE Chinese_PRC_CI_AS NULL ,
[ExceptionType] [nvarchar] (256) COLLATE Chinese_PRC_CI_AS NULL ,
[Details] [ntext] COLLATE Chinese_PRC_CI_AS NULL ,
CONSTRAINT [PK_aspnet_WebEvent_Events] PRIMARY KEY CLUSTERED
(
[EventId]
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [ss_WebEvents] (
[EventId] [char] (32) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[EventTimeUtc] [datetime] NOT NULL ,
[EventTime] [datetime] NOT NULL ,
[EventType] [nvarchar] (256) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[EventSequence] [decimal](19, 0) NOT NULL ,
[EventOccurrence] [decimal](19, 0) NOT NULL ,
[EventCode] [int] NOT NULL ,
[EventDetailCode] [int] NOT NULL ,
[Message] [nvarchar] (1024) COLLATE Chinese_PRC_CI_AS NULL ,
[ApplicationPath] [nvarchar] (256) COLLATE Chinese_PRC_CI_AS NULL ,
[ApplicationVirtualPath] [nvarchar] (256) COLLATE Chinese_PRC_CI_AS NULL ,
[MachineName] [nvarchar] (256) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[RequestUrl] [nvarchar] (1024) COLLATE Chinese_PRC_CI_AS NULL ,
[UserName] [nvarchar] (256) COLLATE Chinese_PRC_CI_AS NULL ,
[ExceptionType] [nvarchar] (256) COLLATE Chinese_PRC_CI_AS NULL ,
[Details] [ntext] COLLATE Chinese_PRC_CI_AS NULL ,
CONSTRAINT [PK_aspnet_WebEvent_Events] PRIMARY KEY CLUSTERED
(
[EventId]
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
第一步 实现事件出来类 SqlWebEventProvider.cs代码如下:
Code
public class SqlWebEventProvider : WebEventProvider
{
const int SQL_MAX_NTEXT_SIZE = 1073741823;
const int NO_LIMIT = -1;
string _sqlConnectionString;
int _maxEventDetailsLength = NO_LIMIT;
int _commandTimeout = -1;
//int _connectionCount = 0;
public override void Initialize(string name, NameValueCollection config)
{
// System.Web.Management.WebAuthenticationSuccessAuditEvent
string connect = null;
connect = config.Get("connectionStringName");
config.Remove("connectionStringName");
_sqlConnectionString = config.Get("connectionString");
config.Remove("connectionString");
if (!String.IsNullOrEmpty(connect))
{
if (!String.IsNullOrEmpty(_sqlConnectionString))
{
throw new ConfigurationErrorsException("SqlWebEventProvider: Specify either a connectionString or connectionStringName, not both.");
}
if (WebConfigurationManager.ConnectionStrings[connect] == null)
throw new ProviderException("Missing connection string");
_sqlConnectionString = WebConfigurationManager.ConnectionStrings[connect].ConnectionString;
if (_sqlConnectionString == null || _sqlConnectionString.Length < 1)
{
throw new ConfigurationErrorsException(String.Format("The connection name '{0}' was not found in the applications configuration or the connection string is empty.", connect));
}
}
else
{
// If a connection string is specified explicitly, verify that its not using integrated security
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(_sqlConnectionString);
if (builder.IntegratedSecurity)
{
throw new ConfigurationErrorsException(String.Format("SqlWebEventProvider: connectionString can only contain connection strings that use Sql Server authentication. Trusted Connection security is not supported."));
}
}
if (String.IsNullOrEmpty(_sqlConnectionString))
{
throw new ConfigurationErrorsException(String.Format("SqlWebEventProvider: Either a connectionString or connectionStringName must be specified.", connect));
}
///////////////////
if (config.Get("maxEventDetailsLength") == null || config.Get("maxEventDetailsLength") == "Infinite")
{
_maxEventDetailsLength = Int32.MaxValue;
}
else
{
_maxEventDetailsLength = int.Parse(config.Get("maxEventDetailsLength"));
}
config.Remove("maxEventDetailsLength");
if (_maxEventDetailsLength == Int32.MaxValue)
{
_maxEventDetailsLength = NO_LIMIT;
}
else if (_maxEventDetailsLength > SQL_MAX_NTEXT_SIZE)
{
throw new ConfigurationErrorsException(String.Format("The value '{1}' specified for the maxEventDetailsLength attribute of the '{0}' provider is invalid. It should be between 0 and 1073741823.", name, _maxEventDetailsLength.ToString(CultureInfo.CurrentCulture)));
}
if (config.Get("commandTimeout") != null)
{
_commandTimeout = int.Parse(config.Get("commandTimeout"));
config.Remove("commandTimeout");
}
base.Initialize(name, config);
}
public override void ProcessEvent(WebBaseEvent e)
{
WebApplicationInformation appInfo = WebBaseEvent.ApplicationInformation;
WebRequestInformation reqInfo = null;
if (e is WebRequestEvent)
{
reqInfo = ((WebRequestEvent)e).RequestInformation;
}
else if (e is WebRequestErrorEvent)
{
reqInfo = ((WebRequestErrorEvent)e).RequestInformation;
}
else if (e is WebErrorEvent)
{
reqInfo = ((WebErrorEvent)e).RequestInformation;
}
else if (e is WebAuditEvent)
{
reqInfo = ((WebAuditEvent)e).RequestInformation;
}
SqlConnection connection = new SqlConnection(_sqlConnectionString);
SqlCommand sqlCommand = new SqlCommand(String.Format("INSERT ss_WebEvents (EventId, EventTimeUtc, EventTime, EventType, EventSequence, EventOccurrence, EventCode, EventDetailCode, Message, ApplicationPath, ApplicationVirtualPath, MachineName, RequestUrl, UserName, ExceptionType, Details) VALUES (@EventId, @EventTimeUtc, @EventTime, @EventType, @EventSequence, @EventOccurrence, @EventCode, @EventDetailCode, @Message, @ApplicationPath, @ApplicationVirtualPath, @MachineName, @RequestUrl, @UserName, @ExceptionType, @Details)"), connection);
sqlCommand.Parameters.Add("@EventId", SqlDbType.Char, 32).Value = e.EventID.ToString("N", CultureInfo.InstalledUICulture); ;
sqlCommand.Parameters.Add("@EventTimeUtc", SqlDbType.DateTime).Value = e.EventTimeUtc;
sqlCommand.Parameters.Add("@EventTime", SqlDbType.DateTime).Value = e.EventTime;
sqlCommand.Parameters.Add("@EventType", SqlDbType.NVarChar, 256).Value = e.GetType().ToString();
sqlCommand.Parameters.Add("@EventSequence", SqlDbType.Decimal).Value = e.EventSequence;
sqlCommand.Parameters.Add("@EventOccurrence", SqlDbType.Decimal).Value = e.EventOccurrence;
sqlCommand.Parameters.Add("@EventCode", SqlDbType.Int).Value = e.EventCode;
sqlCommand.Parameters.Add("@EventDetailCode", SqlDbType.Int).Value = e.EventDetailCode;
sqlCommand.Parameters.Add("@Message", SqlDbType.NVarChar, 1024).Value = e.Message;
sqlCommand.Parameters.Add("@ApplicationPath", SqlDbType.NVarChar, 256).Value = appInfo.ApplicationPath;
sqlCommand.Parameters.Add("@ApplicationVirtualPath", SqlDbType.NVarChar, 256).Value = appInfo.ApplicationVirtualPath;
sqlCommand.Parameters.Add("@MachineName", SqlDbType.NVarChar, 256).Value = appInfo.MachineName;
sqlCommand.Parameters.Add("@RequestUrl", SqlDbType.NVarChar, 1024).Value = reqInfo == null || reqInfo.RequestUrl == null ? Convert.DBNull : reqInfo.RequestUrl;
sqlCommand.Parameters.Add("@UserName", SqlDbType.NVarChar, 256).Value = reqInfo == null ? Convert.DBNull : reqInfo.Principal.Identity.Name;
sqlCommand.Parameters.Add("@ExceptionType", SqlDbType.NVarChar, 256).Value = e is WebBaseErrorEvent ? ((WebBaseErrorEvent)e).ErrorException.GetType().ToString() : Convert.DBNull;
sqlCommand.Parameters.Add("@Details", SqlDbType.NText).Value = e.ToString();
if (connection.State == ConnectionState.Closed)
connection.Open();
sqlCommand.ExecuteNonQuery();
}
public override void Flush() { }
public override void Shutdown() { }
}
public class SqlWebEventProvider : WebEventProvider
{
const int SQL_MAX_NTEXT_SIZE = 1073741823;
const int NO_LIMIT = -1;
string _sqlConnectionString;
int _maxEventDetailsLength = NO_LIMIT;
int _commandTimeout = -1;
//int _connectionCount = 0;
public override void Initialize(string name, NameValueCollection config)
{
// System.Web.Management.WebAuthenticationSuccessAuditEvent
string connect = null;
connect = config.Get("connectionStringName");
config.Remove("connectionStringName");
_sqlConnectionString = config.Get("connectionString");
config.Remove("connectionString");
if (!String.IsNullOrEmpty(connect))
{
if (!String.IsNullOrEmpty(_sqlConnectionString))
{
throw new ConfigurationErrorsException("SqlWebEventProvider: Specify either a connectionString or connectionStringName, not both.");
}
if (WebConfigurationManager.ConnectionStrings[connect] == null)
throw new ProviderException("Missing connection string");
_sqlConnectionString = WebConfigurationManager.ConnectionStrings[connect].ConnectionString;
if (_sqlConnectionString == null || _sqlConnectionString.Length < 1)
{
throw new ConfigurationErrorsException(String.Format("The connection name '{0}' was not found in the applications configuration or the connection string is empty.", connect));
}
}
else
{
// If a connection string is specified explicitly, verify that its not using integrated security
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(_sqlConnectionString);
if (builder.IntegratedSecurity)
{
throw new ConfigurationErrorsException(String.Format("SqlWebEventProvider: connectionString can only contain connection strings that use Sql Server authentication. Trusted Connection security is not supported."));
}
}
if (String.IsNullOrEmpty(_sqlConnectionString))
{
throw new ConfigurationErrorsException(String.Format("SqlWebEventProvider: Either a connectionString or connectionStringName must be specified.", connect));
}
///////////////////
if (config.Get("maxEventDetailsLength") == null || config.Get("maxEventDetailsLength") == "Infinite")
{
_maxEventDetailsLength = Int32.MaxValue;
}
else
{
_maxEventDetailsLength = int.Parse(config.Get("maxEventDetailsLength"));
}
config.Remove("maxEventDetailsLength");
if (_maxEventDetailsLength == Int32.MaxValue)
{
_maxEventDetailsLength = NO_LIMIT;
}
else if (_maxEventDetailsLength > SQL_MAX_NTEXT_SIZE)
{
throw new ConfigurationErrorsException(String.Format("The value '{1}' specified for the maxEventDetailsLength attribute of the '{0}' provider is invalid. It should be between 0 and 1073741823.", name, _maxEventDetailsLength.ToString(CultureInfo.CurrentCulture)));
}
if (config.Get("commandTimeout") != null)
{
_commandTimeout = int.Parse(config.Get("commandTimeout"));
config.Remove("commandTimeout");
}
base.Initialize(name, config);
}
public override void ProcessEvent(WebBaseEvent e)
{
WebApplicationInformation appInfo = WebBaseEvent.ApplicationInformation;
WebRequestInformation reqInfo = null;
if (e is WebRequestEvent)
{
reqInfo = ((WebRequestEvent)e).RequestInformation;
}
else if (e is WebRequestErrorEvent)
{
reqInfo = ((WebRequestErrorEvent)e).RequestInformation;
}
else if (e is WebErrorEvent)
{
reqInfo = ((WebErrorEvent)e).RequestInformation;
}
else if (e is WebAuditEvent)
{
reqInfo = ((WebAuditEvent)e).RequestInformation;
}
SqlConnection connection = new SqlConnection(_sqlConnectionString);
SqlCommand sqlCommand = new SqlCommand(String.Format("INSERT ss_WebEvents (EventId, EventTimeUtc, EventTime, EventType, EventSequence, EventOccurrence, EventCode, EventDetailCode, Message, ApplicationPath, ApplicationVirtualPath, MachineName, RequestUrl, UserName, ExceptionType, Details) VALUES (@EventId, @EventTimeUtc, @EventTime, @EventType, @EventSequence, @EventOccurrence, @EventCode, @EventDetailCode, @Message, @ApplicationPath, @ApplicationVirtualPath, @MachineName, @RequestUrl, @UserName, @ExceptionType, @Details)"), connection);
sqlCommand.Parameters.Add("@EventId", SqlDbType.Char, 32).Value = e.EventID.ToString("N", CultureInfo.InstalledUICulture); ;
sqlCommand.Parameters.Add("@EventTimeUtc", SqlDbType.DateTime).Value = e.EventTimeUtc;
sqlCommand.Parameters.Add("@EventTime", SqlDbType.DateTime).Value = e.EventTime;
sqlCommand.Parameters.Add("@EventType", SqlDbType.NVarChar, 256).Value = e.GetType().ToString();
sqlCommand.Parameters.Add("@EventSequence", SqlDbType.Decimal).Value = e.EventSequence;
sqlCommand.Parameters.Add("@EventOccurrence", SqlDbType.Decimal).Value = e.EventOccurrence;
sqlCommand.Parameters.Add("@EventCode", SqlDbType.Int).Value = e.EventCode;
sqlCommand.Parameters.Add("@EventDetailCode", SqlDbType.Int).Value = e.EventDetailCode;
sqlCommand.Parameters.Add("@Message", SqlDbType.NVarChar, 1024).Value = e.Message;
sqlCommand.Parameters.Add("@ApplicationPath", SqlDbType.NVarChar, 256).Value = appInfo.ApplicationPath;
sqlCommand.Parameters.Add("@ApplicationVirtualPath", SqlDbType.NVarChar, 256).Value = appInfo.ApplicationVirtualPath;
sqlCommand.Parameters.Add("@MachineName", SqlDbType.NVarChar, 256).Value = appInfo.MachineName;
sqlCommand.Parameters.Add("@RequestUrl", SqlDbType.NVarChar, 1024).Value = reqInfo == null || reqInfo.RequestUrl == null ? Convert.DBNull : reqInfo.RequestUrl;
sqlCommand.Parameters.Add("@UserName", SqlDbType.NVarChar, 256).Value = reqInfo == null ? Convert.DBNull : reqInfo.Principal.Identity.Name;
sqlCommand.Parameters.Add("@ExceptionType", SqlDbType.NVarChar, 256).Value = e is WebBaseErrorEvent ? ((WebBaseErrorEvent)e).ErrorException.GetType().ToString() : Convert.DBNull;
sqlCommand.Parameters.Add("@Details", SqlDbType.NText).Value = e.ToString();
if (connection.State == ConnectionState.Closed)
connection.Open();
sqlCommand.ExecuteNonQuery();
}
public override void Flush() { }
public override void Shutdown() { }
}
第三步:配置web.config
Code
<healthMonitoring enabled="true">
<eventMappings>
<clear />
<add name="All Events"
type="System.Web.Management.WebBaseEvent"
startEventCode="0"
endEventCode="2147483647" />
</eventMappings>
<providers>
<clear />
<add name="DefaultEventProvider"
type="SqlWebEventProvider"
logFileName="~/App_Data/Contosolog.txt"
connectionStringName="ConnectionString" />
</providers>
<rules>
<clear />
<add name="All WebEvent Default"
eventName="All Events"
provider="DefaultEventProvider"
profile="Default"
minInstances="1"
maxLimit="Infinite"
minInterval="00:00:00"
custom="" />
</rules>
</healthMonitoring>
<healthMonitoring enabled="true">
<eventMappings>
<clear />
<add name="All Events"
type="System.Web.Management.WebBaseEvent"
startEventCode="0"
endEventCode="2147483647" />
</eventMappings>
<providers>
<clear />
<add name="DefaultEventProvider"
type="SqlWebEventProvider"
logFileName="~/App_Data/Contosolog.txt"
connectionStringName="ConnectionString" />
</providers>
<rules>
<clear />
<add name="All WebEvent Default"
eventName="All Events"
provider="DefaultEventProvider"
profile="Default"
minInstances="1"
maxLimit="Infinite"
minInterval="00:00:00"
custom="" />
</rules>
</healthMonitoring>