using Longbow; using Longbow.Configuration; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; namespace Bootstrap.DataAccess { /// /// /// public class Log { /// /// 获得/设置 操作日志主键ID /// public string Id { get; set; } /// /// 获得/设置 操作类型 /// public string CRUD { get; set; } /// /// 获得/设置 用户名称 /// public string UserName { get; set; } /// /// 获得/设置 操作时间 /// public DateTime LogTime { get; set; } /// /// 获得/设置 客户端IP /// public string ClientIp { get; set; } /// /// 获取/设置 客户端信息 /// public string ClientAgent { get; set; } /// /// 获取/设置 请求网址 /// public string RequestUrl { get; set; } /// /// 查询所有日志信息 /// /// /// public virtual IEnumerable RetrieveLogs() { string sql = "select * from Logs where LogTime > @LogTime"; List logs = new List(); 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()) { logs.Add(new Log() { Id = reader[0].ToString(), CRUD = (string)reader[1], UserName = (string)reader[2], LogTime = LgbConvert.ReadValue(reader[3], DateTime.MinValue), ClientIp = (string)reader[4], ClientAgent = (string)reader[5], RequestUrl = (string)reader[6] }); } } return logs; } /// /// 删除日志信息 /// /// /// private static void DeleteLogAsync() { System.Threading.Tasks.Task.Run(() => { string sql = $"delete from Logs 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["KeepLogsPeriod"], 1)), DbType.DateTime)); DbAccessManager.DBAccess.ExecuteNonQuery(cmd); }); } /// /// 保存新增的日志信息 /// /// /// public virtual bool SaveLog(Log p) { if (p == null) throw new ArgumentNullException(nameof(p)); bool ret = false; string sql = "Insert Into Logs (CRUD, UserName, LogTime, ClientIp, ClientAgent, RequestUrl) Values (@CRUD, @UserName, @LogTime, @ClientIp, @ClientAgent, @RequestUrl)"; using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) { cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@CRUD", p.CRUD)); cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserName", p.UserName)); cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@LogTime", DateTime.Now, DbType.DateTime)); cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ClientIp", p.ClientIp)); cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ClientAgent", p.ClientAgent)); cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RequestUrl", p.RequestUrl)); ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; } DeleteLogAsync(); return ret; } } }