Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Logging 记录RestServiceBase请求和响应_Logging_<img Src="//i.stack.imgur.com/WM7S8.png" Height="16" Width="18" Alt="" Class="sponsor Tag Img">servicestack - Fatal编程技术网 servicestack,Logging,servicestack" /> servicestack,Logging,servicestack" />

Logging 记录RestServiceBase请求和响应

Logging 记录RestServiceBase请求和响应,logging,servicestack,Logging,servicestack,我正在使用一个仍然引用RestServiceBase的旧项目,我知道需要记录此API的所有调用请求和响应 我可以轻松地浏览每个服务实现,并添加如下内容: // get reponse from request object response = this.OnGetSpecificAccount(request); // log Logs.LogRequestWithResponse( this.RequestContext, this.Request.Http

我正在使用一个仍然引用
RestServiceBase
的旧项目,我知道需要记录此API的所有调用请求和响应

我可以轻松地浏览每个服务实现,并添加如下内容:

// get reponse from request
object response = this.OnGetSpecificAccount(request);

// log
Logs.LogRequestWithResponse(
                this.RequestContext, this.Request.HttpMethod, response.ToJson());
在提取并插入数据库后,我会得到一个如下所示的日志:


但是我想知道是否已经有了一些日志记录实现,我可以利用它们,并且可以轻松地连接到基类并自动记录,因为我也想记录
Auth
调用(为了获得正在验证的
用户名
,并将
用户名
会话

匹配,您可以使用记录所有请求/响应。在我的公司,一位同事实现了将此信息保存到数据库的功能。但是,我们不记录响应

更新有人要求我们的实现。我们最初使用NewtonSoft.Json来表示Json,但我无法在UI中看到请求数据,因为它是反序列化的。因此我切换到Servicestack Json,它按预期工作。如下所示:

DatabaseLoggingFeature.cs

   public class DatabaseLoggingFeature : IPlugin
{
    public DatabaseLoggingFeature(string connectionStringKey, int? capacity = null)
    {
        AtRestPath = "/requestlogs";
        ConnectionStringKey = connectionStringKey;
        Capacity = capacity;
        RequiredRoles = new[] {RoleNames.Admin};
        EnableErrorTracking = true;
        EnableRequestBodyTracking = false;
        ExcludeRequestDtoTypes = new[] {typeof (RequestLogs), typeof (ResourceRequest), typeof (Resources)};
        HideRequestBodyForRequestDtoTypes = new[]
        {
            typeof (Auth), typeof (Registration)
        };
    }

    /// <summary>
    ///     Gets or sets connection string
    /// </summary>
    public string ConnectionStringKey { get; set; }

    /// <summary>
    ///     RequestLogs service Route, default is /requestlogs
    /// </summary>
    public string AtRestPath { get; set; }

    /// <summary>
    ///     Turn On/Off Session Tracking
    /// </summary>
    public bool EnableSessionTracking { get; set; }

    /// <summary>
    ///     Turn On/Off Logging of Raw Request Body, default is Off
    /// </summary>
    public bool EnableRequestBodyTracking { get; set; }

    /// <summary>
    ///     Turn On/Off Tracking of Responses
    /// </summary>
    public bool EnableResponseTracking { get; set; }

    /// <summary>
    ///     Turn On/Off Tracking of Exceptions
    /// </summary>
    public bool EnableErrorTracking { get; set; }

    /// <summary>
    ///     Size of InMemoryRollingRequestLogger circular buffer
    /// </summary>
    public int? Capacity { get; set; }

    /// <summary>
    ///     Limit access to /requestlogs service to these roles
    /// </summary>
    public string[] RequiredRoles { get; set; }

    /// <summary>
    ///     Change the RequestLogger provider. Default is InMemoryRollingRequestLogger
    /// </summary>
    public IRequestLogger RequestLogger { get; set; }

    /// <summary>
    ///     Don't log requests of these types. By default RequestLog's are excluded
    /// </summary>
    public Type[] ExcludeRequestDtoTypes { get; set; }

    /// <summary>
    ///     Don't log request body's for services with sensitive information.
    ///     By default Auth and Registration requests are hidden.
    /// </summary>
    public Type[] HideRequestBodyForRequestDtoTypes { get; set; }

    /// <summary>
    ///     Registers plugin with service stack
    /// </summary>
    /// <param name="appHost">Application Host configuration object.</param>
    public void Register(IAppHost appHost)
    {
        appHost.RegisterService<RequestLogsService>(AtRestPath);

        IRequestLogger requestLogger = RequestLogger ?? new DatabaseRequestLogger(ConnectionStringKey);
        requestLogger.EnableSessionTracking = EnableSessionTracking;
        requestLogger.EnableResponseTracking = EnableResponseTracking;
        requestLogger.EnableRequestBodyTracking = EnableRequestBodyTracking;
        requestLogger.EnableErrorTracking = EnableErrorTracking;
        requestLogger.RequiredRoles = RequiredRoles;
        requestLogger.ExcludeRequestDtoTypes = ExcludeRequestDtoTypes;
        requestLogger.HideRequestBodyForRequestDtoTypes = HideRequestBodyForRequestDtoTypes;

        appHost.Register(requestLogger);

        if (EnableRequestBodyTracking)
        {
            appHost.PreRequestFilters.Insert(0,
                (httpReq, httpRes) => { httpReq.UseBufferedStream = EnableRequestBodyTracking; });
        }
    }
}
public class DatabaseRequestLogger : IRequestLogger
{
    /// <summary>
    ///     Instance of the current database connection;
    /// </summary>
    private readonly DbConnection _connection;

    public DatabaseRequestLogger(string connectionStringKey)
    {
        if (string.IsNullOrEmpty(connectionStringKey))
        {
            throw new ArgumentNullException("connectionStringKey");
        }

        if (_connection != null || string.IsNullOrEmpty(connectionStringKey)) return;
        ConnectionStringSettingsCollection connectionStrings = ConfigurationManager.ConnectionStrings;

        if (connectionStrings == null) return;
        foreach (ConnectionStringSettings setting in connectionStrings.Cast<ConnectionStringSettings>()
            .Where(setting => setting.Name == connectionStringKey))
        {
            ConnectionString = setting.ConnectionString;
            ProviderName = setting.ProviderName;
            _connection = GetConnection(ProviderName, ConnectionString);
        }
    }

    public ILog log { get; set; }

    /// <summary>
    ///     Gets connection string
    /// </summary>
    public string ConnectionString { get; private set; }

    /// <summary>
    ///     Gets provider name
    /// </summary>
    public string ProviderName { get; private set; }

    /// <summary>
    /// </summary>
    public bool EnableErrorTracking { get; set; }

    /// <summary>
    /// </summary>
    public bool EnableRequestBodyTracking { get; set; }

    /// <summary>
    /// </summary>
    public bool EnableResponseTracking { get; set; }

    /// <summary>
    /// </summary>
    public bool EnableSessionTracking { get; set; }

    /// <summary>
    /// </summary>
    public Type[] ExcludeRequestDtoTypes { get; set; }

    /// <summary>
    ///     Returns latest log entries.
    /// </summary>
    /// <param name="take">number of records to retrieve.</param>
    /// <returns>List of RequestLogEntry</returns>
    public List<RequestLogEntry> GetLatestLogs(int? take)
    {
        var entries = new List<RequestLogEntry>();

        if (_connection != null)
        {
            if (_connection.State == ConnectionState.Closed)
            {
                _connection.Open();
            }

            using (DbCommand cmd = _connection.CreateCommand())
            {
                string query = "SELECT {0} FROM [dbo].[RequestLog] ORDER BY LoggedDate DESC";

                query = take.HasValue
                    ? string.Format(query, "TOP " + take.Value.ToString(CultureInfo.InvariantCulture) + " * ")
                    : string.Format(query, "*");

                cmd.Connection = _connection;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = query;

                try
                {
                    DbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                    while (dr.Read())
                    {
                        var serializer = new JsonSerializer<RequestLogEntry>();

                        RequestLogEntry entry = serializer.DeserializeFromString(dr["LogEntry"].ToString());

                        entries.Add(entry);
                    }
                }
                catch (Exception)
                {
                    cmd.Parameters.Clear();

                    if (cmd.Connection.State == ConnectionState.Open)
                    {
                        cmd.Connection.Close();
                    }
                }
            }
        }

        return entries;
    }

    /// <summary>
    /// </summary>
    public Type[] HideRequestBodyForRequestDtoTypes { get; set; }

    /// <summary>
    /// </summary>
    public string[] RequiredRoles { get; set; }

    /// <summary>
    ///     Logs request/response data.
    /// </summary>
    /// <param name="requestDto"></param>
    /// <param name="response">instance of <see cref="IHttpResponse" /> object.</param>
    /// <param name="requestContext"></param>
    /// <param name="duration"></param>
    public void Log(IRequestContext requestContext, object requestDto, object response, TimeSpan duration)
    {
        Type requestType = requestDto != null ? requestDto.GetType() : null;

        // if we don't want to track the request simply bail out.
        if (ExcludeRequestDtoTypes != null
            && requestType != null
            && ExcludeRequestDtoTypes.Contains(requestType))
        {
            return;
        }

        //Move this code to another class and create an interface

        if (_connection != null)
        {
            if (_connection.State == ConnectionState.Closed)
            {
                _connection.Open();
            }

            using (DbCommand cmd = _connection.CreateCommand())
            {
                cmd.Connection = _connection;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "spLogRequest";

                var entry = new RequestLogEntry
                {
                    DateTime = DateTime.UtcNow,
                    RequestDuration = duration
                };

                IHttpRequest httpRequest = requestContext != null ? requestContext.Get<IHttpRequest>() : null;

                if (httpRequest != null)
                {
                    entry.HttpMethod = httpRequest.HttpMethod;
                    entry.AbsoluteUri = httpRequest.AbsoluteUri;
                    entry.PathInfo = httpRequest.PathInfo;
                    entry.IpAddress = requestContext.IpAddress;
                    entry.Headers = httpRequest.Headers.ToDictionary();
                    entry.Referer = httpRequest.Headers[HttpHeaders.Referer];
                    entry.ForwardedFor = httpRequest.Headers[HttpHeaders.XForwardedFor];
                    entry.RequestDto = requestDto;
                    entry.Items = httpRequest.Items;
                    entry.UserAuthId = httpRequest.GetItemOrCookie(HttpHeaders.XUserAuthId);
                    entry.SessionId = httpRequest.GetSessionId();
                    entry.Session = EnableSessionTracking ? httpRequest.GetSession() : null;

                    if (HideRequestBodyForRequestDtoTypes != null
                        && requestType != null
                        && !HideRequestBodyForRequestDtoTypes.Contains(requestType))
                    {
                        entry.RequestDto = requestDto;

                        entry.FormData = httpRequest.FormData.ToDictionary();

                        if (EnableRequestBodyTracking)
                        {
                            entry.RequestBody = httpRequest.GetRawBody();
                        }
                    }

                    if (!response.IsErrorResponse())
                    {
                        if (EnableResponseTracking)
                        {
                            entry.ResponseDto = response;
                        }
                    }
                }

                DbParameter requestParam = cmd.CreateParameter();
                requestParam.ParameterName = "@LogEntry";
                requestParam.Direction = ParameterDirection.Input;
                requestParam.DbType = DbType.String;
                //JsConfig.IncludeTypeInfo = true;
                requestParam.Value = new JsonSerializer<RequestLogEntry>().SerializeToString(entry);

                DbParameter requestDurationParam = cmd.CreateParameter();
                requestDurationParam.ParameterName = "@RequestDuration";
                requestDurationParam.Direction = ParameterDirection.Input;
                requestDurationParam.DbType = DbType.Int64;
                requestDurationParam.Value = entry.RequestDuration.Ticks;

                cmd.Parameters.Add(requestParam);
                cmd.Parameters.Add(requestDurationParam);

                try
                {
                    cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                }
                catch (Exception ex)
                {
                    log.Error("Error occurred saving request log entry to the database in Log.", ex);
                }
                finally
                {
                    cmd.Parameters.Clear();

                    if (cmd.Connection.State == ConnectionState.Open)
                    {
                        cmd.Connection.Close();
                    }
                }
            }
        }
    }
公共类数据库日志功能:IPlugin
{
公共数据库记录功能(字符串连接stringkey,int?capacity=null)
{
AtRestPath=“/requestlogs”;
ConnectionStringKey=ConnectionStringKey;
容量=容量;
RequiredRoles=new[]{RoleNames.Admin};
EnableErrorTracking=true;
EnableRequestBodyTracking=false;
ExcludeRequestDtoTypes=new[]{typeof(RequestLogs)、typeof(ResourceRequest)、typeof(Resources)};
HidereRequestBodyForRequestdToTypes=new[]
{
typeof(认证),typeof(注册)
};
}
/// 
///获取或设置连接字符串
/// 
公共字符串连接字符串key{get;set;}
/// 
///RequestLogs服务路由,默认为/RequestLogs
/// 
公共字符串AtRestPath{get;set;}
/// 
///打开/关闭会话跟踪
/// 
public bool EnableSessionTracking{get;set;}
/// 
///打开/关闭原始请求主体的日志记录,默认为关闭
/// 
public bool EnableRequestBodyTracking{get;set;}
/// 
///打开/关闭响应跟踪
/// 
public bool EnableResponseTracking{get;set;}
/// 
///打开/关闭异常跟踪
/// 
public bool EnableErrorTracking{get;set;}
/// 
///InMemoryRollingRequestLogger循环缓冲区的大小
/// 
公共int?容量{get;set;}
/// 
///将对/requestlogs服务的访问限制为这些角色
/// 
公共字符串[]RequiredRoles{get;set;}
/// 
///更改RequestLogger提供程序。默认值为InMemoryRollingRequestLogger
/// 
公共IRequestLogger请求记录器{get;set;}
/// 
///不记录这些类型的请求。默认情况下,将排除RequestLog
/// 
公共类型[]ExcludeRequestDtoTypes{get;set;}
/// 
///不要记录带有敏感信息的服务的请求主体。
///默认情况下,身份验证和注册请求是隐藏的。
/// 
公共类型[]HiderRequestBodyForRequestdToTypes{get;set;}
/// 
///向服务堆栈注册插件
/// 
///应用程序主机配置对象。
公共无效寄存器(IAppHost-appHost)
{
注册服务(AtRestPath);
IRequestLogger requestLogger=requestLogger??新数据库requestLogger(ConnectionStringKey);
requestLogger.EnableSessionTracking=EnableSessionTracking;
requestLogger.EnableResponseTracking=EnableResponseTracking;
requestLogger.EnableRequestBodyTracking=EnableRequestBodyTracking;
requestLogger.EnableErrorTracking=EnableErrorTracking;
requestLogger.RequiredRoles=RequiredRoles;
requestLogger.ExcludeRequestDtoTypes=ExcludeRequestDtoTypes;
requestLogger.HideRequestBodyForRequestDtoTypes=HideRequestBodyForRequestDtoTypes;
appHost.Register(请求记录器);
如果(启用RequestBodyTracking)
{
appHost.PreRequestFilters.Insert(0,
(httpReq,httpRes)=>{httpReq.UseBufferedStream=EnableRequestBodyTracking;});
}
}
}
DatabaseRequestLogger.cs

   public class DatabaseLoggingFeature : IPlugin
{
    public DatabaseLoggingFeature(string connectionStringKey, int? capacity = null)
    {
        AtRestPath = "/requestlogs";
        ConnectionStringKey = connectionStringKey;
        Capacity = capacity;
        RequiredRoles = new[] {RoleNames.Admin};
        EnableErrorTracking = true;
        EnableRequestBodyTracking = false;
        ExcludeRequestDtoTypes = new[] {typeof (RequestLogs), typeof (ResourceRequest), typeof (Resources)};
        HideRequestBodyForRequestDtoTypes = new[]
        {
            typeof (Auth), typeof (Registration)
        };
    }

    /// <summary>
    ///     Gets or sets connection string
    /// </summary>
    public string ConnectionStringKey { get; set; }

    /// <summary>
    ///     RequestLogs service Route, default is /requestlogs
    /// </summary>
    public string AtRestPath { get; set; }

    /// <summary>
    ///     Turn On/Off Session Tracking
    /// </summary>
    public bool EnableSessionTracking { get; set; }

    /// <summary>
    ///     Turn On/Off Logging of Raw Request Body, default is Off
    /// </summary>
    public bool EnableRequestBodyTracking { get; set; }

    /// <summary>
    ///     Turn On/Off Tracking of Responses
    /// </summary>
    public bool EnableResponseTracking { get; set; }

    /// <summary>
    ///     Turn On/Off Tracking of Exceptions
    /// </summary>
    public bool EnableErrorTracking { get; set; }

    /// <summary>
    ///     Size of InMemoryRollingRequestLogger circular buffer
    /// </summary>
    public int? Capacity { get; set; }

    /// <summary>
    ///     Limit access to /requestlogs service to these roles
    /// </summary>
    public string[] RequiredRoles { get; set; }

    /// <summary>
    ///     Change the RequestLogger provider. Default is InMemoryRollingRequestLogger
    /// </summary>
    public IRequestLogger RequestLogger { get; set; }

    /// <summary>
    ///     Don't log requests of these types. By default RequestLog's are excluded
    /// </summary>
    public Type[] ExcludeRequestDtoTypes { get; set; }

    /// <summary>
    ///     Don't log request body's for services with sensitive information.
    ///     By default Auth and Registration requests are hidden.
    /// </summary>
    public Type[] HideRequestBodyForRequestDtoTypes { get; set; }

    /// <summary>
    ///     Registers plugin with service stack
    /// </summary>
    /// <param name="appHost">Application Host configuration object.</param>
    public void Register(IAppHost appHost)
    {
        appHost.RegisterService<RequestLogsService>(AtRestPath);

        IRequestLogger requestLogger = RequestLogger ?? new DatabaseRequestLogger(ConnectionStringKey);
        requestLogger.EnableSessionTracking = EnableSessionTracking;
        requestLogger.EnableResponseTracking = EnableResponseTracking;
        requestLogger.EnableRequestBodyTracking = EnableRequestBodyTracking;
        requestLogger.EnableErrorTracking = EnableErrorTracking;
        requestLogger.RequiredRoles = RequiredRoles;
        requestLogger.ExcludeRequestDtoTypes = ExcludeRequestDtoTypes;
        requestLogger.HideRequestBodyForRequestDtoTypes = HideRequestBodyForRequestDtoTypes;

        appHost.Register(requestLogger);

        if (EnableRequestBodyTracking)
        {
            appHost.PreRequestFilters.Insert(0,
                (httpReq, httpRes) => { httpReq.UseBufferedStream = EnableRequestBodyTracking; });
        }
    }
}
public class DatabaseRequestLogger : IRequestLogger
{
    /// <summary>
    ///     Instance of the current database connection;
    /// </summary>
    private readonly DbConnection _connection;

    public DatabaseRequestLogger(string connectionStringKey)
    {
        if (string.IsNullOrEmpty(connectionStringKey))
        {
            throw new ArgumentNullException("connectionStringKey");
        }

        if (_connection != null || string.IsNullOrEmpty(connectionStringKey)) return;
        ConnectionStringSettingsCollection connectionStrings = ConfigurationManager.ConnectionStrings;

        if (connectionStrings == null) return;
        foreach (ConnectionStringSettings setting in connectionStrings.Cast<ConnectionStringSettings>()
            .Where(setting => setting.Name == connectionStringKey))
        {
            ConnectionString = setting.ConnectionString;
            ProviderName = setting.ProviderName;
            _connection = GetConnection(ProviderName, ConnectionString);
        }
    }

    public ILog log { get; set; }

    /// <summary>
    ///     Gets connection string
    /// </summary>
    public string ConnectionString { get; private set; }

    /// <summary>
    ///     Gets provider name
    /// </summary>
    public string ProviderName { get; private set; }

    /// <summary>
    /// </summary>
    public bool EnableErrorTracking { get; set; }

    /// <summary>
    /// </summary>
    public bool EnableRequestBodyTracking { get; set; }

    /// <summary>
    /// </summary>
    public bool EnableResponseTracking { get; set; }

    /// <summary>
    /// </summary>
    public bool EnableSessionTracking { get; set; }

    /// <summary>
    /// </summary>
    public Type[] ExcludeRequestDtoTypes { get; set; }

    /// <summary>
    ///     Returns latest log entries.
    /// </summary>
    /// <param name="take">number of records to retrieve.</param>
    /// <returns>List of RequestLogEntry</returns>
    public List<RequestLogEntry> GetLatestLogs(int? take)
    {
        var entries = new List<RequestLogEntry>();

        if (_connection != null)
        {
            if (_connection.State == ConnectionState.Closed)
            {
                _connection.Open();
            }

            using (DbCommand cmd = _connection.CreateCommand())
            {
                string query = "SELECT {0} FROM [dbo].[RequestLog] ORDER BY LoggedDate DESC";

                query = take.HasValue
                    ? string.Format(query, "TOP " + take.Value.ToString(CultureInfo.InvariantCulture) + " * ")
                    : string.Format(query, "*");

                cmd.Connection = _connection;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = query;

                try
                {
                    DbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                    while (dr.Read())
                    {
                        var serializer = new JsonSerializer<RequestLogEntry>();

                        RequestLogEntry entry = serializer.DeserializeFromString(dr["LogEntry"].ToString());

                        entries.Add(entry);
                    }
                }
                catch (Exception)
                {
                    cmd.Parameters.Clear();

                    if (cmd.Connection.State == ConnectionState.Open)
                    {
                        cmd.Connection.Close();
                    }
                }
            }
        }

        return entries;
    }

    /// <summary>
    /// </summary>
    public Type[] HideRequestBodyForRequestDtoTypes { get; set; }

    /// <summary>
    /// </summary>
    public string[] RequiredRoles { get; set; }

    /// <summary>
    ///     Logs request/response data.
    /// </summary>
    /// <param name="requestDto"></param>
    /// <param name="response">instance of <see cref="IHttpResponse" /> object.</param>
    /// <param name="requestContext"></param>
    /// <param name="duration"></param>
    public void Log(IRequestContext requestContext, object requestDto, object response, TimeSpan duration)
    {
        Type requestType = requestDto != null ? requestDto.GetType() : null;

        // if we don't want to track the request simply bail out.
        if (ExcludeRequestDtoTypes != null
            && requestType != null
            && ExcludeRequestDtoTypes.Contains(requestType))
        {
            return;
        }

        //Move this code to another class and create an interface

        if (_connection != null)
        {
            if (_connection.State == ConnectionState.Closed)
            {
                _connection.Open();
            }

            using (DbCommand cmd = _connection.CreateCommand())
            {
                cmd.Connection = _connection;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "spLogRequest";

                var entry = new RequestLogEntry
                {
                    DateTime = DateTime.UtcNow,
                    RequestDuration = duration
                };

                IHttpRequest httpRequest = requestContext != null ? requestContext.Get<IHttpRequest>() : null;

                if (httpRequest != null)
                {
                    entry.HttpMethod = httpRequest.HttpMethod;
                    entry.AbsoluteUri = httpRequest.AbsoluteUri;
                    entry.PathInfo = httpRequest.PathInfo;
                    entry.IpAddress = requestContext.IpAddress;
                    entry.Headers = httpRequest.Headers.ToDictionary();
                    entry.Referer = httpRequest.Headers[HttpHeaders.Referer];
                    entry.ForwardedFor = httpRequest.Headers[HttpHeaders.XForwardedFor];
                    entry.RequestDto = requestDto;
                    entry.Items = httpRequest.Items;
                    entry.UserAuthId = httpRequest.GetItemOrCookie(HttpHeaders.XUserAuthId);
                    entry.SessionId = httpRequest.GetSessionId();
                    entry.Session = EnableSessionTracking ? httpRequest.GetSession() : null;

                    if (HideRequestBodyForRequestDtoTypes != null
                        && requestType != null
                        && !HideRequestBodyForRequestDtoTypes.Contains(requestType))
                    {
                        entry.RequestDto = requestDto;

                        entry.FormData = httpRequest.FormData.ToDictionary();

                        if (EnableRequestBodyTracking)
                        {
                            entry.RequestBody = httpRequest.GetRawBody();
                        }
                    }

                    if (!response.IsErrorResponse())
                    {
                        if (EnableResponseTracking)
                        {
                            entry.ResponseDto = response;
                        }
                    }
                }

                DbParameter requestParam = cmd.CreateParameter();
                requestParam.ParameterName = "@LogEntry";
                requestParam.Direction = ParameterDirection.Input;
                requestParam.DbType = DbType.String;
                //JsConfig.IncludeTypeInfo = true;
                requestParam.Value = new JsonSerializer<RequestLogEntry>().SerializeToString(entry);

                DbParameter requestDurationParam = cmd.CreateParameter();
                requestDurationParam.ParameterName = "@RequestDuration";
                requestDurationParam.Direction = ParameterDirection.Input;
                requestDurationParam.DbType = DbType.Int64;
                requestDurationParam.Value = entry.RequestDuration.Ticks;

                cmd.Parameters.Add(requestParam);
                cmd.Parameters.Add(requestDurationParam);

                try
                {
                    cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                }
                catch (Exception ex)
                {
                    log.Error("Error occurred saving request log entry to the database in Log.", ex);
                }
                finally
                {
                    cmd.Parameters.Clear();

                    if (cmd.Connection.State == ConnectionState.Open)
                    {
                        cmd.Connection.Close();
                    }
                }
            }
        }
    }
公共类数据库请求记录器:IRequestLogger { /// ///当前数据库连接的实例; /// 专用只读DbConnection\u连接; 公共数据库请求记录器(字符串连接stringkey) { if(string.IsNullOrEmpty(connectionStringKey)) { 抛出新ArgumentNullException(“connectionStringKey”); } if(_connection!=null | | string.IsNullOrEmpty(connectionStringKey))返回; ConnectionString设置集合ConnectionString=ConfigurationManager.ConnectionString; if(connectionString==null)返回; foreach(connectionStrings.Cast()中的ConnectionStringSettings设置) .Where(setting=>setting.Name==connectionStringKey)) { ConnectionString=setting.ConnectionString; ProviderName=setting.ProviderName; _connection=GetConnection(ProviderName,ConnectionString); } } 公共ILog日志{get;set;} /// ///获取连接字符串 /// 公共字符串连接字符串{get;private set;} /// ///获取提供程序名称 /// 公共字符串提供程序名称{get;private set;} /// /// public bool EnableErrorTracking{get;set;} /// /// public bool EnableRequestBodyTracking{get;set;} /// /// public bool EnableResponseTracking{get;set;} ///