重构系统日志架构,稍后完善

This commit is contained in:
Argo-Lenovo 2016-11-05 15:26:42 +08:00
parent aa4bf3c989
commit 3a2c89f289
12 changed files with 284 additions and 384 deletions

View File

@ -129,7 +129,6 @@
<Content Include="Content\fonts\glyphicons-halflings-regular.svg" />
<Content Include="Content\images\success.png" />
<Content Include="Content\js\common-scripts.js" />
<Content Include="Content\js\jQuery.cookie.js" />
<Content Include="Content\js\jquery.dcjqaccordion.2.7.js" />
<Content Include="Content\js\jquery.nicescroll.min.js" />
<Content Include="Content\js\jquery.scrollTo.js" />

View File

@ -1,7 +1,8 @@
(function ($) {
BootstrapAdmin = function (options) {
var that = this;
if (options.click !== undefined && options.click.constructor === Object) { options.click = $.extend({}, BootstrapAdmin.settings.click, options.click); }
options = options || {};
options.click = $.extend({}, BootstrapAdmin.settings.click, options.click);
this.options = $.extend({}, BootstrapAdmin.settings, options);
this.dataEntity = options.dataEntity;
@ -144,7 +145,7 @@
type: 'DELETE',
success: function (result) {
if ($.isFunction(options.success)) options.success('del', options);
if (result) setTimeout(function () { swal("成功!", "删除数据", "success"); $(options.bootstrapTable).bootstrapTable('refresh'); saveLog(options, "DELETE"); }, 100);
if (result) setTimeout(function () { swal("成功!", "删除数据", "success"); $(options.bootstrapTable).bootstrapTable('refresh'); }, 100);
else setTimeout(function () { swal("失败", "删除数据", "error"); }, 200);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
@ -183,7 +184,6 @@
}
}
if (options.modal.constructor === String) $('#' + options.modal).modal("hide");
saveLog(options, "POST");
swal("成功", "保存数据", "success");
}
else {

View File

@ -1,89 +0,0 @@
/*jslint browser: true */ /*global jQuery: true */
/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
// TODO JsDoc
/**
* Create a cookie with the given key and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
* used when the cookie was set.
*
* @param String key The key of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
* Get the value of a cookie with the given key.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String key The key of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function (key, value, options) {
// key and value given, set cookie...
if (arguments.length > 1 && (value === null || typeof value !== "object")) {
options = jQuery.extend({}, options);
if (value === null) {
options.expires = -1;
}
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
return (document.cookie = [
encodeURIComponent(key), '=',
options.raw ? String(value) : encodeURIComponent(String(value)),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// key and possibly options given, get cookie...
options = value || {};
var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

View File

@ -1,30 +1,38 @@
var saveLog = function (options,otype) {
$.ajax({
url: "../api/Logs",
type: "POST",
data: CreateOperationData(options,otype),
success: function (result) {
if (result) {
}
}
(function ($) {
LogPlugin = function (options) {
var that = this;
this.options = $.extend({}, LogPlugin.settings, options);
// handler click event
for (name in this.options.click) {
var cId = this.options.click[name];
var source = $("#" + cId);
source.data('click', name);
source.click(function () {
var method = $(this).data('click');
LogPlugin.prototype[method].call(that, this);
});
}
function CreateOperationData(options,otype) {
var nameStr = $.cookie("lgb____bd____cp");
nameStr = nameStr.substring("realUserName=".length, nameStr.indexOf("&"));
var operationType;
if (otype == "POST") {
//0表示新增1表示修改
operationType = options.data.ID == 0 ? 0 : 1;
} else if (otype == "DELETE") {
//2表示删除
operationType = 2;
}
//operationModule表示修改的模块
var operationModule = options.url.substring(options.url.lastIndexOf("/") + 1, options.url.length);
var postdata = { OperationType: operationType, UserName: nameStr, Remark: "", OperationModule: operationModule };
return postdata;
LogPlugin.settings = {
url: '../api/Logs',
click: {
query: 'btn_query',
del: 'btn_delete',
save: 'btnSubmit'
}
}
LogPlugin.prototype = {
constructor: LogPlugin,
query: function (element) {
log(this.options.url, { crud: 'Query' });
}
}
var log = function (url, data) {
$.post(url, data);
}
})(jQuery);

View File

@ -1,6 +1,7 @@
using Bootstrap.Admin.Models;
using Bootstrap.DataAccess;
using System.Linq;
using System.Web;
using System.Web.Http;
namespace Bootstrap.Admin.Controllers
@ -31,9 +32,11 @@ namespace Bootstrap.Admin.Controllers
[HttpPost]
public bool Post([FromBody]Log value)
{
value.OperationIp = LogHelper.GetClientIp();
value.OperationTime = System.DateTime.Now;
var request = HttpContext.Current.Request;
value.ClientAgent = request.UserAgent;
value.RequestUrl = request.Url.AbsolutePath;
value.ClientIp = request.UserHostAddress;
value.UserName = HttpContext.Current.User.Identity.Name;
return LogHelper.SaveLog(value);
}
}

View File

@ -25,26 +25,25 @@ namespace Bootstrap.Admin.Models
var data = LogHelper.RetrieveLogs(string.Empty);
if (!string.IsNullOrEmpty(OperateType))
{
data = data.Where(t => t.OperationType.ToString().Contains(OperateType));
data = data.Where(t => t.CRUD.ToString().Contains(OperateType));
}
if (!string.IsNullOrEmpty(OperateTimeStart))
{
DateTime opTimeStart = StringToDateTime(OperateTimeStart);
if (opTimeStart != null)
data = data.Where(t => IsSmallThen(opTimeStart, t.OperationTime));
data = data.Where(t => IsSmallThen(opTimeStart, t.LogTime));
}
if (!string.IsNullOrEmpty(OperateTimeEnd))
{
DateTime opTimeEnd = StringToDateTime(OperateTimeEnd);
if (opTimeEnd != null)
data = data.Where(t => IsSmallThen(t.OperationTime, opTimeEnd));
data = data.Where(t => IsSmallThen(t.LogTime, opTimeEnd));
}
var ret = new QueryData<Log>();
ret.total = data.Count();
// TODO: 通过option.Sort属性判断对那列进行排序现在统一对名称列排序
data = Order == "asc" ? data.OrderBy(t => t.OperationType) : data.OrderByDescending(t => t.OperationType);
data = Order == "asc" ? data.OrderBy(t => t.CRUD) : data.OrderByDescending(t => t.CRUD);
ret.rows = data.Skip(Offset).Take(Limit);
return ret;
}

View File

@ -1,37 +1,21 @@
$(function () {
//隐藏掉操作按钮
$("#toolbar").hide();
var bsa = new BootstrapAdmin({
url: '../api/Logs',
dataEntity: new DataEntity({
map: {
ID: "logID",
OperationType: "operateType",
UserID: "userId",
OperationTime: "operateTime",
OperateIp: "operationIp",
OperationModule: "operationModule",
}
})
});
$('table').smartTable({
url: '../api/Logs', //请求后台的URL*
sortName: 'OperationType',
queryParams: function (params) { return $.extend(params, { operateType: $("#txt_operate_type").val(), OperateTimeStart: $("#txt_operate_start").val(), OperateTimeEnd: $("#txt_operate_end").val() }); }, //传递参数(*
columns: [{ checkbox: true },
{ title: "Id", field: "ID", events: bsa.idEvents(), formatter: BootstrapAdmin.idFormatter, },
{ title: "操作类型", field: "OperationType", sortable: true },
{ title: "操作类型", field: "CRUD", sortable: true },
{ title: "用户名称", field: "UserName", sortable: false },
{
title: "操作时间", field: "OperationTime", sortable: false,
title: "操作时间", field: "LogTime", sortable: false,
formatter: function (value, row, index) {
return value.substring(0, 19).replace("T", " ");
}
},
{ title: "操作IP", field: "OperationIp", sortable: false },
{ title: "备注", field: "Remark", sortable: false },
{ title: "操作模块", field: "OperationModule", sortable: false }
{ title: "操作IP", field: "ClientIp", sortable: false },
{ title: "备注", field: "ClientAgent", sortable: false },
{ title: "操作模块", field: "RequestUrl", sortable: false }
]
});
var log = new LogPlugin();
});

View File

@ -1,9 +1,11 @@
@model NavigatorBarModel
@{
ViewBag.Title = "系统日志";
Layout = "~/Views/Shared/_Default.cshtml";
Layout = "~/Views/Shared/_Admin.cshtml";
}
@section Javascript {
<script src="~/content/js/bootstrap-table.js"></script>
<script src="~/content/js/bootstrap-table-zh-CN.js"></script>
<script src="~/scripts/Logs.js"></script>
}
@section header {
@ -12,7 +14,9 @@
@section navigator {
@Html.Partial("Navigator", Model)
}
@section query {
<div class="panel panel-default">
<div class="panel-heading">查询条件</div>
<div class="panel-body">
<form class="form-inline" role="form">
<div class="form-group col-lg-5">
<label class="control-label" for="txt_operate_type">操作类型</label>
@ -26,9 +30,17 @@
<label class="control-label" for="txt_operate_end">终止时间</label>
<input type="datetime" class="form-control" id="txt_operate_end" />
</div>
<div class="form-group col-lg-2">
<button type="button" id="btn_query" class="btn btn-primary"><span class="glyphicon glyphicon-search" aria-hidden="true"></span>查询</button>
</div>
</form>
}
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
查询结果
</div>
<div class="panel-body">
<table></table>
</div>
</div>

View File

@ -11,7 +11,7 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 操作类型
/// </summary>
public int OperationType { get; set; }
public string CRUD { get; set; }
/// <summary>
/// 获得/设置 用户名称
@ -21,21 +21,21 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 操作时间
/// </summary>
public DateTime OperationTime { get; set; }
public DateTime LogTime { get; set; }
/// <summary>
/// 获得/设置 操作者Ip
/// 获得/设置 客户端IP
/// </summary>
public string OperationIp { get; set; }
public string ClientIp { get; set; }
/// <summary>
/// 获取/设置 备注
/// 获取/设置 客户端信息
/// </summary>
public string Remark { get; set; }
public string ClientAgent { get; set; }
/// <summary>
/// 获取/设置 操作模块
/// 获取/设置 请求网址
/// </summary>
public string OperationModule { get; set; }
public string RequestUrl { get; set; }
}
}

View File

@ -35,12 +35,12 @@ namespace Bootstrap.DataAccess
Logs.Add(new Log()
{
ID = (int)reader[0],
OperationType = (int)reader[1],
CRUD = (string)reader[1],
UserName = (string)reader[2],
OperationTime = (DateTime)reader[3],
OperationIp = (string)reader[4],
Remark = (string)reader[5],
OperationModule = (string)reader[6]
LogTime = (DateTime)reader[3],
ClientIp = (string)reader[4],
ClientAgent = (string)reader[5],
RequestUrl = (string)reader[6]
});
}
}
@ -84,17 +84,16 @@ namespace Bootstrap.DataAccess
{
if (p == null) throw new ArgumentNullException("p");
bool ret = false;
string sql = "Insert Into Logs (OperationType, UserName,OperationTime,OperationIp,Remark,OperationModule) Values (@OperationType, @UserName,@OperationTime,@OperationIp,@Remark,@OperationModule)";
string sql = "Insert Into Logs (CRUD, UserName, LogTime, ClientIp, ClientAgent, RequestUrl) Values (@CRUD, @UserName, GetDate(), @ClientIp, @ClientAgent, @RequestUrl)";
try
{
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@OperationType", p.OperationType, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@CRUD", p.CRUD, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@UserName", p.UserName, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@OperationTime", p.OperationTime, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@OperationIp", p.OperationIp == null ? "" : p.OperationIp, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@Remark", p.Remark == null ? "" : p.Remark, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@OperationModule", p.OperationModule == null ? "" : p.OperationModule, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@ClientIp", p.ClientIp, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@ClientAgent", p.ClientAgent, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@RequestUrl", p.RequestUrl, ParameterDirection.Input));
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd);
}
CacheCleanUtility.ClearCache(logIds: p.ID == 0 ? "" : p.ID.ToString());
@ -106,21 +105,5 @@ namespace Bootstrap.DataAccess
}
return ret;
}
/// <summary>
/// 获取客户端IP地址
/// </summary>
/// <returns></returns>
public static string GetClientIp()
{
HttpRequest request = HttpContext.Current.Request;
string result = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(result))
result = request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(result))
result = request.UserHostAddress;
if (string.IsNullOrEmpty(result))
result = "0.0.0.0";
return result;
}
}
}

View File

@ -36,11 +36,6 @@ EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'密码盐' , @
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'显示名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Users', @level2type=N'COLUMN',@level2name=N'DisplayName'
GO
/* added by argo the default password is 123789 */
insert into Users (UserName, Password, PassSalt, DisplayName) values ('Admin', 'Es7WVgNsJuELwWK8daCqufUBknCsSC0IYDphQZAiGOo=', 'W5vpBEOYRGHkQXatN0t+ECM/U8cHDuEgrq56+zZBk4J481xH', 'Administrator')
GO
/****** Object: Table [dbo].[Groups] Script Date: 10/22/2016 09:44:03 ******/
SET ANSI_NULLS ON
GO
@ -180,33 +175,39 @@ EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'字典代码'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0表示系统使用1表示自定义' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Dicts', @level2type=N'COLUMN',@level2name=N'Define'
GO
/****** Object: Table [dbo].[Logs] Script Date: 11/04/2016 15:13:04 ******/
/****** Object: Table [dbo].[Logs] Script Date: 11/05/2016 14:17:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Logs](
[ID] [int] IDENTITY(1,1) NOT NULL,
[OperationType] [int] NOT NULL,
[CRUD] [varchar](50) NOT NULL,
[UserName] [varchar](50) NOT NULL,
[OperationTime] [datetime] NOT NULL,
[OperationIp] [nvarchar](50) NULL,
[Remark] [nvarchar](500) NULL,
[OperationModule] [varchar](50) NULL,
[LogTime] [datetime] NOT NULL,
[ClientIp] [varchar](15) NOT NULL,
[ClientAgent] [nvarchar](500) NOT NULL,
[RequestUrl] [nvarchar](500) NOT NULL,
CONSTRAINT [PK_Logs] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Logs', @level2type=N'COLUMN',@level2name=N'ID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Logs', @level2type=N'COLUMN',@level2name=N'OperationType'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Logs', @level2type=N'COLUMN',@level2name=N'CURD'
GO
/****** Object: Table [dbo].[Navigations] ******/
CREATE TABLE [dbo].[Navigations](