在请求WebApi 的时候,我们更想知道在请求数据的时候,调用了哪个接口传了什么参数过来,调用这个Action花了多少时间,有没有人恶意请求。我们可以通过记录日志,对Action进行优化,可以通过日志追踪是哪个用户或ip恶意请求。
在项目中引用log4net.dll
定义一个WebApiMonitorLog ,监控日志对象
///
/// 监控日志对象
///
public class WebApiMonitorLog
{
public string ControllerName { get; set; }
public string ActionName { get; set; }
public DateTime ExecuteStartTime { get; set; }
public DateTime ExecuteEndTime { get; set; }
///
/// 请求的Action 参数
///
public Dictionary ActionParams { get; set; }
///
/// Http请求头
///
public string HttpRequestHeaders { get; set; }
///
/// 请求方式
///
public string HttpMethod { get; set; }
///
/// 请求的IP地址
///
public string IP { get; set; }
///
/// 获取监控指标日志
///
///
///
public string GetLoginfo()
{
string Msg = @"
Action执行时间监控:
ControllerName:{0}Controller
ActionName:{1}
开始时间:{2}
结束时间:{3}
总 时 间:{4}秒
Action参数:{5}
Http请求头:{6}
客户端IP:{7},
HttpMethod:{8}
";
return string.Format(Msg,
ControllerName,
ActionName,
ExecuteStartTime,
ExecuteEndTime,
(ExecuteEndTime - ExecuteStartTime).TotalSeconds,
GetCollections(ActionParams),
HttpRequestHeaders,
IP,
HttpMethod);
}
///
/// 获取Action 参数
///
///
///
public string GetCollections(Dictionary Collections)
{
string Parameters = string.Empty;
if (Collections == null || Collections.Count == 0)
{
return Parameters;
}
foreach (string key in Collections.Keys)
{
Parameters += string.Format("{0}={1}&", key, Collections[key]);
}
if (!string.IsNullOrWhiteSpace(Parameters) && Parameters.EndsWith("&"))
{
Parameters = Parameters.Substring(0, Parameters.Length - 1);
}
return Parameters;
}
///
/// 获取IP
///
///
public string GetIP()
{
string ip = string.Empty;
if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
if (string.IsNullOrEmpty(ip))
ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
return ip;
}
}
定义一个LoggerHelper,日志帮助类
public class LoggerHelper
{
private static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
private static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
private static readonly log4net.ILog logmonitor = log4net.LogManager.GetLogger("logmonitor");
public static void Error(string ErrorMsg, Exception ex = null)
{
if (ex != null)
{
logerror.Error(ErrorMsg, ex);
}
else
{
logerror.Error(ErrorMsg);
}
}
public static void Info(string Msg)
{
loginfo.Info(Msg);
}
public static void Monitor(string Msg)
{
logmonitor.Info(Msg);
}
}
定义一个WebApiTrackerAttribute类,继承于ActionFilterAttribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class WebApiTrackerAttribute : ActionFilterAttribute
{
private readonly string Key = "_thisWebApiOnActionMonitorLog_";
public override void OnActionExecuting(HttpActionContext actionContext) {
base.OnActionExecuting(actionContext);
WebApiMonitorLog MonLog = new WebApiMonitorLog();
MonLog.ExecuteStartTime = DateTime.Now;
//获取Action 参数
MonLog.ActionParams = actionContext.ActionArguments;
MonLog.HttpRequestHeaders = actionContext.Request.Headers.ToString();
MonLog.HttpMethod = actionContext.Request.Method.Method;
actionContext.Request.Properties[Key] = MonLog;
var form = System.Web.HttpContext.Current.Request.Form;
#region 如果参数是实体对象,获取序列化后的数据
Stream stream = actionContext.Request.Content.ReadAsStreamAsync().Result;
Encoding encoding = Encoding.UTF8;
stream.Position = 0;
string responseData = "";
using (StreamReader reader = new StreamReader(stream, encoding)) {
responseData = reader.ReadToEnd().ToString();
}
if (!string.IsNullOrWhiteSpace(responseData) && !MonLog.ActionParams.ContainsKey("__EntityParamsList__")) {
MonLog.ActionParams["__EntityParamsList__"] = responseData;
}
#endregion
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
WebApiMonitorLog MonLog = actionExecutedContext.Request.Properties[Key] as WebApiMonitorLog;
MonLog.ExecuteEndTime = DateTime.Now;
MonLog.ActionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
MonLog.ControllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
LoggerHelper.Monitor(MonLog.GetLoginfo());
if (actionExecutedContext.Exception != null) {
string Msg = string.Format(@"
请求【{0}Controller】的【{1}】产生异常:
Action参数:{2}
Http请求头:{3}
客户端IP:{4},
HttpMethod:{5}
", MonLog.ControllerName, MonLog.ActionName, MonLog.GetCollections(MonLog.ActionParams), MonLog.HttpRequestHeaders, MonLog.GetIP(), MonLog.HttpMethod);
LoggerHelper.Error(Msg, actionExecutedContext.Exception);
}
}
}
新建一个log4net.config
然后引用监控,在Global.asax 里加上这段
GlobalConfiguration.Configuration.Filters.Add(new WebApiTrackerAttribute());
AreaRegistration.RegisterAllAreas();
最后在需要监控的控制器上加上 WebApiTracker
每次在调用这个监控下的Action 时,都会有日志记录,像这样滴
在项目下有个log 文件夹
参考于:http://www.cnblogs.com/lc-chenlong/p/4228639.html log4net 记录MVC监控日志
感谢感谢!!
若日志没有生成,补充:
1 没有在AssemblyInfo文件中添加下面的代码:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
2 运行程序目录下没有log4net.config配置文件。
选择解决方案中的log4net.config,在属性–>复制到输出目录,选择始终复制