重构代码:重写Exceptions表相关SQL语句,子类直接使用即可

This commit is contained in:
Argo-MacBookPro 2018-11-02 18:31:32 +08:00
parent 64f02c469a
commit 575adc78aa
7 changed files with 150 additions and 174 deletions

View File

@ -1,92 +1,10 @@
using Longbow;
using Longbow.Configuration;
using Longbow.Data;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.Common;
namespace Bootstrap.DataAccess.MySQL
namespace Bootstrap.DataAccess.MySQL
{
/// <summary>
///
/// </summary>
public class Exceptions : DataAccess.Exceptions
{
/// <summary>
///
/// </summary>
private static void ClearExceptions()
{
System.Threading.Tasks.Task.Run(() =>
{
string sql = $"delete from Exceptions where LogTime < date_add(now(), interval -{ConfigurationManager.AppSettings["KeepExceptionsPeriod"]} month)";
DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql);
DbAccessManager.DBAccess.ExecuteNonQuery(cmd);
});
}
/// <summary>
///
/// </summary>
/// <param name="ex"></param>
/// <param name="additionalInfo"></param>
/// <returns></returns>
public override bool Log(Exception ex, NameValueCollection additionalInfo)
{
if (additionalInfo == null)
{
additionalInfo = new NameValueCollection
{
["UserId"] = null,
["UserIp"] = null,
["ErrorPage"] = null
};
}
var errorPage = additionalInfo["ErrorPage"] ?? ex.GetType().Name;
var sql = "insert into Exceptions (AppDomainName, ErrorPage, UserID, UserIp, ExceptionType, Message, StackTrace, LogTime) values (@AppDomainName, @ErrorPage, @UserID, @UserIp, @ExceptionType, @Message, @StackTrace, now())";
using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql))
{
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@AppDomainName", AppDomain.CurrentDomain.FriendlyName));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ErrorPage", errorPage));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserID", DbAdapterManager.ToDBValue(additionalInfo["UserId"])));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserIp", DbAdapterManager.ToDBValue(additionalInfo["UserIp"])));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ExceptionType", ex.GetType().FullName));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Message", ex.Message));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@StackTrace", DbAdapterManager.ToDBValue(ex.StackTrace)));
DbAccessManager.DBAccess.ExecuteNonQuery(cmd);
ClearExceptions();
}
return true;
}
/// <summary>
/// 查询一周内所有异常
/// </summary>
/// <returns></returns>
public override IEnumerable<DataAccess.Exceptions> RetrieveExceptions()
{
string sql = "select * from Exceptions where LogTime > date_add(now(), interval -7 day) order by LogTime desc";
List<DataAccess.Exceptions> exceptions = new List<DataAccess.Exceptions>();
DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql);
using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd))
{
while (reader.Read())
{
exceptions.Add(new DataAccess.Exceptions()
{
Id = reader[0].ToString(),
AppDomainName = (string)reader[1],
ErrorPage = reader.IsDBNull(2) ? string.Empty : (string)reader[2],
UserId = reader.IsDBNull(3) ? string.Empty : (string)reader[3],
UserIp = reader.IsDBNull(4) ? string.Empty : (string)reader[4],
ExceptionType = (string)reader[5],
Message = (string)reader[6],
StackTrace = (string)reader[7],
LogTime = LgbConvert.ReadValue(reader[8], DateTime.MinValue)
});
}
}
return exceptions;
}
}
}

View File

@ -1,92 +1,10 @@
using Longbow;
using Longbow.Configuration;
using Longbow.Data;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.Common;
namespace Bootstrap.DataAccess.SQLite
namespace Bootstrap.DataAccess.SQLite
{
/// <summary>
///
/// </summary>
public class Exceptions : DataAccess.Exceptions
{
/// <summary>
///
/// </summary>
private static void ClearExceptions()
{
System.Threading.Tasks.Task.Run(() =>
{
string sql = $"delete from Exceptions where LogTime < datetime('now', 'localtime', '-{ConfigurationManager.AppSettings["KeepExceptionsPeriod"]} month')";
DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql);
DbAccessManager.DBAccess.ExecuteNonQuery(cmd);
});
}
/// <summary>
///
/// </summary>
/// <param name="ex"></param>
/// <param name="additionalInfo"></param>
/// <returns></returns>
public override bool Log(Exception ex, NameValueCollection additionalInfo)
{
if (additionalInfo == null)
{
additionalInfo = new NameValueCollection
{
["UserId"] = null,
["UserIp"] = null,
["ErrorPage"] = null
};
}
var errorPage = additionalInfo["ErrorPage"] ?? ex.GetType().Name;
var sql = "insert into Exceptions (AppDomainName, ErrorPage, UserID, UserIp, ExceptionType, Message, StackTrace, LogTime) values (@AppDomainName, @ErrorPage, @UserID, @UserIp, @ExceptionType, @Message, @StackTrace, datetime('now', 'localtime'))";
using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql))
{
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@AppDomainName", AppDomain.CurrentDomain.FriendlyName));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ErrorPage", errorPage));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserID", DbAdapterManager.ToDBValue(additionalInfo["UserId"])));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserIp", DbAdapterManager.ToDBValue(additionalInfo["UserIp"])));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ExceptionType", ex.GetType().FullName));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Message", ex.Message));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@StackTrace", DbAdapterManager.ToDBValue(ex.StackTrace)));
DbAccessManager.DBAccess.ExecuteNonQuery(cmd);
ClearExceptions();
}
return true;
}
/// <summary>
/// 查询一周内所有异常
/// </summary>
/// <returns></returns>
public override IEnumerable<DataAccess.Exceptions> RetrieveExceptions()
{
string sql = "select * from Exceptions where LogTime > datetime('now', 'localtime', '-7 day') order by LogTime desc";
List<DataAccess.Exceptions> exceptions = new List<DataAccess.Exceptions>();
DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql);
using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd))
{
while (reader.Read())
{
exceptions.Add(new DataAccess.Exceptions()
{
Id = reader[0].ToString(),
AppDomainName = (string)reader[1],
ErrorPage = reader.IsDBNull(2) ? string.Empty : (string)reader[2],
UserId = reader.IsDBNull(3) ? string.Empty : (string)reader[3],
UserIp = reader.IsDBNull(4) ? string.Empty : (string)reader[4],
ExceptionType = (string)reader[5],
Message = (string)reader[6],
StackTrace = (string)reader[7],
LogTime = LgbConvert.ReadValue(reader[8], DateTime.MinValue)
});
}
}
return exceptions;
}
}
}

View File

@ -1,4 +1,5 @@
using Longbow.Configuration;
using Longbow;
using Longbow.Configuration;
using Longbow.Data;
using System;
using System.Collections.Generic;
@ -58,8 +59,9 @@ namespace Bootstrap.DataAccess
{
System.Threading.Tasks.Task.Run(() =>
{
string sql = $"delete from Exceptions where LogTime < DATEADD(MONTH, -{ConfigurationManager.AppSettings["KeepExceptionsPeriod"]}, GETDATE())";
string sql = $"delete from Exceptions where LogTime < @LogTime";
DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql);
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@LogTime", DateTime.Now.AddMonths(0 - LgbConvert.ReadValue(ConfigurationManager.AppSettings["KeepExceptionsPeriod"], 1)), DbType.DateTime));
DbAccessManager.DBAccess.ExecuteNonQuery(cmd);
});
}
@ -82,7 +84,7 @@ namespace Bootstrap.DataAccess
};
}
var errorPage = additionalInfo["ErrorPage"] ?? (ex.GetType().Name.Length > 50 ? ex.GetType().Name.Substring(0, 50) : ex.GetType().Name);
var sql = "insert into Exceptions (AppDomainName, ErrorPage, UserID, UserIp, ExceptionType, Message, StackTrace, LogTime) values (@AppDomainName, @ErrorPage, @UserID, @UserIp, @ExceptionType, @Message, @StackTrace, GetDate())";
var sql = "insert into Exceptions (AppDomainName, ErrorPage, UserID, UserIp, ExceptionType, Message, StackTrace, LogTime) values (@AppDomainName, @ErrorPage, @UserID, @UserIp, @ExceptionType, @Message, @StackTrace, @LogTime)";
using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql))
{
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@AppDomainName", AppDomain.CurrentDomain.FriendlyName));
@ -92,6 +94,7 @@ namespace Bootstrap.DataAccess
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ExceptionType", ex.GetType().FullName));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Message", ex.Message));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@StackTrace", DbAdapterManager.ToDBValue(ex.StackTrace)));
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@LogTime", DateTime.Now, DbType.DateTime));
DbAccessManager.DBAccess.ExecuteNonQuery(cmd);
ClearExceptions();
}
@ -103,9 +106,10 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public virtual IEnumerable<Exceptions> RetrieveExceptions()
{
string sql = "select * from Exceptions where DATEDIFF(Week, LogTime, GETDATE()) = 0 order by LogTime desc";
string sql = "select * from Exceptions where LogTime > @LogTime order by LogTime desc";
List<Exceptions> exceptions = new List<Exceptions>();
DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql);
cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@LogTime", DateTime.Now.AddDays(-7), DbType.DateTime));
using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd))
{
while (reader.Read())

View File

@ -0,0 +1,98 @@
using Bootstrap.DataAccess;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace UnitTest
{
public class ExceptionsTest
{
[Fact]
public void RetrieveExceptions_Array()
{
var config = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddInMemoryCollection(new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("DB:0:Enabled", "true"),
new KeyValuePair<string, string>("DB:0:Widget", "Bootstrap.DataAccess"),
new KeyValuePair<string, string>("DB:0:ConnectionStrings:ba", "Data Source=.;Initial Catalog=BootstrapAdmin;User ID=sa;Password=sa")
})
.Build();
new ServiceCollection()
.AddSingleton<IConfiguration>(config)
.AddConfigurationManager(config)
.AddDbAdapter(config);
Exceptions excep = new Exceptions();
var result = excep.RetrieveExceptions();
var num = result.Count();
Assert.True(num >= 0);
}
[Fact]
public void RetrieveExceptions_SQLite_Array()
{
var config = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddInMemoryCollection(new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("DB:0:Enabled", "true"),
new KeyValuePair<string, string>("DB:0:Widget", "Bootstrap.DataAccess.SQLite"),
new KeyValuePair<string, string>("DB:0:DBProviderFactory", "Microsoft.Data.Sqlite.SqliteFactory, Microsoft.Data.Sqlite"),
new KeyValuePair<string, string>("DB:0:ConnectionStrings:ba", "Data Source=BootstrapAdmin.db;")
})
.Build();
new ServiceCollection()
.AddSingleton<IConfiguration>(config)
.AddConfigurationManager(config)
.AddDbAdapter(config);
Exceptions excep = new Exceptions();
var result = excep.RetrieveExceptions();
var num = result.Count();
Assert.True(num >= 0);
}
[Fact]
public void RetrieveExceptions_MySQL_Array()
{
var config = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddInMemoryCollection(new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("DB:0:Enabled", "true"),
new KeyValuePair<string, string>("DB:0:Widget", "Bootstrap.DataAccess.MySQL"),
new KeyValuePair<string, string>("DB:0:DBProviderFactory", "MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data"),
new KeyValuePair<string, string>("DB:0:ConnectionStrings:ba", "Server=10.211.55.2;Database=BA;Uid=argozhang;Pwd=argo@163.com;SslMode=none;")
})
.Build();
new ServiceCollection()
.AddSingleton<IConfiguration>(config)
.AddConfigurationManager(config)
.AddDbAdapter(config);
Exceptions excep = new Exceptions();
var result = excep.RetrieveExceptions();
var num = result.Count();
Assert.True(num >= 0);
}
[Fact]
public async void ClearExceptions_Void()
{
StaticMethods.Setup();
Exceptions excep = new Exceptions();
var method = excep.GetType().GetMethod("ClearExceptions", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
method.Invoke(excep, null);
await System.Threading.Tasks.Task.Delay(1000);
}
}
}

23
UnitTest/StaticMethods.cs Normal file
View File

@ -0,0 +1,23 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace UnitTest
{
internal static class StaticMethods
{
public static void Setup()
{
var config = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile("appsettings.Development.json", true, true)
.Build();
new ServiceCollection()
.AddSingleton<IConfiguration>(config)
.AddConfigurationManager(config)
.AddDbAdapter(config);
}
}
}

View File

@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetLatestRuntimePatch>true</TargetLatestRuntimePatch>
<IsPackable>false</IsPackable>
</PropertyGroup>
@ -10,6 +10,15 @@
<Compile Include="..\Bootstrap.Admin\Startup.cs" Link="Startup.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="..\Bootstrap.Admin\appsettings.Development.json" Link="appsettings.Development.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="..\Bootstrap.Admin\appsettings.json" Link="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.5" />
@ -21,4 +30,11 @@
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Bootstrap.Admin\Bootstrap.Admin.csproj" />
<ProjectReference Include="..\Bootstrap.DataAccess.MySQL\Bootstrap.DataAccess.MySQL.csproj" />
<ProjectReference Include="..\Bootstrap.DataAccess.SQLite\Bootstrap.DataAccess.SQLite.csproj" />
<ProjectReference Include="..\Bootstrap.DataAccess\Bootstrap.DataAccess.csproj" />
</ItemGroup>
</Project>

View File

@ -13,7 +13,6 @@ namespace UnitTest
{
var server = new TestServer(WebHost.CreateDefaultBuilder()
.UseStartup<Startup>());
}
}
}