ASP.NET web API项目添加日志输出与C#日志输出存在一点小小的差异,C#中只需要放配置文件就可以了,而ASP.NET log需要配置并在启动文件中加入启动读取配置文件和相关的日志过滤器。在C#和ASP.NET中使用的日志包是log4net。
只需要编辑一个log4.config文件到bin的对应版本下就可以了。
在项目中新建一个Logs文件夹,然后添加如下几个类到里面:
LoggerHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace RTVSApiFD.Logs
{
///
/// 日志帮助类
///
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");
///
/// 记录Error日志
///
///
///
public static void Error(string errorMsg, Exception ex = null)
{
if (ex != null)
{
LogError.Error(errorMsg, ex);
}
else
{
LogError.Error(errorMsg);
}
}
///
/// 记录Info日志
///
///
///
public static void Info(string msg, Exception ex = null)
{
if (ex != null)
{
LogInfo.Info(msg, ex);
}
else
{
LogInfo.Info(msg);
}
}
///
/// 记录Monitor日志
///
///
public static void Monitor(string msg)
{
LogMonitor.Info(msg);
}
}
}
MonitorLog.cs
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Web;
namespace RTVSApiFD.Logs
{
///
/// 监控日志对象
///
public class MonitorLog
{
///
/// 构造函数
///
public MonitorLog()
{
this.Watch = new Stopwatch();
this.Watch.Start();
}
///
/// 监控类型
///
public enum MonitorType
{
///
/// Action
///
Action = 1,
///
/// 视图
///
View = 2
}
///
///
///
public string ControllerName { get; set; }
///
///
///
public string ActionName { get; set; }
///
///
///
public Stopwatch Watch { get; set; }
///
///
///
public DateTime ExecuteStartTime { get; set; }
///
///
///
public DateTime ExecuteEndTime { get; set; }
///
/// Form 表单数据
///
public NameValueCollection FormCollections { get; set; }
///
/// URL 参数
///
public NameValueCollection QueryCollections { get; set; }
///
/// 文本流
///
public string Raw { get; set; }
///
/// 获取监控指标日志
///
///
///
public string GetLogInfo(MonitorType mtype = MonitorType.Action)
{
this.Watch.Stop();
string actionView = "Action执行时间监控:";
string action = "Action";
if (mtype == MonitorType.View)
{
actionView = "View视图生成时间监控:";
action = "View";
}
string msgContent = string.Format(@"{0}ControllerName:{1}Controller {2}Name:{3} 开始时间:{4} 结束时间:{5} 总 时 间:{6}秒",
actionView,
this.ControllerName,
action,
this.ActionName,
this.ExecuteStartTime,
this.ExecuteEndTime,
this.Watch.ElapsedMilliseconds);
if (!string.IsNullOrEmpty(this.Raw))
{
msgContent += @"
Raw:" + this.Raw;
}
else if (this.FormCollections != null)
{
msgContent += @"
Form:" + this.GetCollections(this.FormCollections);
}
else if (this.QueryCollections != null)
{
msgContent += @"
Query:" + this.GetCollections(this.QueryCollections);
}
return msgContent;
}
///
/// 获取Post 或Get 参数
///
///
///
public string GetCollections(NameValueCollection collections)
{
string parameters = string.Empty;
if (collections == null || collections.Count == 0)
{
return parameters;
}
parameters = collections.Keys.Cast()
.Aggregate(parameters, (current, key) => current + string.Format("{0}={1}&", key, collections[key]));
if (!string.IsNullOrWhiteSpace(parameters) && parameters.EndsWith("&"))
{
parameters = parameters.Substring(0, parameters.Length - 1);
}
return parameters;
}
}
}
TrackerFilter.cs
using System;
using System.Globalization;
using System.Web.Mvc;
namespace RTVSApiFD.Logs
{
///
/// 跟踪过滤器
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class TrackerFilter : System.Web.Mvc.ActionFilterAttribute,System.Web.Mvc.IActionFilter,System.Web.Mvc.IResultFilter,System.Web.Mvc.IExceptionFilter
{
private readonly string key = "_thisOnActionMonitorLog_";
#region Action时间监控
///
/// OnActionExecuting
///
///
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
MonitorLog monLog = new MonitorLog();
monLog.ExecuteStartTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ffff", DateTimeFormatInfo.InvariantInfo));
monLog.ControllerName = filterContext.RouteData.Values["controller"] as string;
monLog.ActionName = filterContext.RouteData.Values["action"] as string;
filterContext.Controller.ViewData[this.key] = monLog;
}
///
/// OnActionExecuted
///
///
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
MonitorLog monLog = filterContext.Controller.ViewData[this.key] as MonitorLog;
monLog.ExecuteEndTime = DateTime.Now;
monLog.FormCollections = filterContext.HttpContext.Request.Form;//form表单提交的数据
monLog.QueryCollections = filterContext.HttpContext.Request.QueryString;//Url 参数
LoggerHelper.Monitor(monLog.GetLogInfo());
}
#endregion
#region View 视图生成时间监控
///
/// OnResultExecuting
///
///
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
MonitorLog monLog = filterContext.Controller.ViewData[this.key] as MonitorLog;
monLog.ExecuteStartTime = DateTime.Now;
}
///
/// OnResultExecuted
///
///
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
MonitorLog monLog = filterContext.Controller.ViewData[this.key] as MonitorLog;
monLog.ExecuteEndTime = DateTime.Now;
LoggerHelper.Monitor(monLog.GetLogInfo(MonitorLog.MonitorType.View));
filterContext.Controller.ViewData.Remove(this.key);
}
#endregion
#region 错误日志
///
/// OnException
///
///
public void OnException(ExceptionContext filterContext)
{
if (!filterContext.ExceptionHandled)
{
string controllerName = string.Format("{0}Controller", filterContext.RouteData.Values["controller"] as string);
string actionName = filterContext.RouteData.Values["action"] as string;
string errorMsg = string.Format("在执行 controller[{0}] 的 action[{1}] 时产生异常", controllerName, actionName);
LoggerHelper.Error(errorMsg, filterContext.Exception);
}
}
///
/// OnAuthorization
///
///
public void OnAuthorization(AuthorizationContext filterContext)
{
这个方法是在Action执行之前调用
//var user = filterContext.HttpContext.Session["userName"];
//if (user == null)
//{
// //filterConetext.HttpContext.Response.Redirect("/Login/index");
// var url = new UrlHelper(filterContext.RequestContext);
// var urls = url.Action("Index", "Login");
// filterContext.Result = new RedirectResult(urls);
//}
}
#endregion
}
}
ApiTrackerFilter.cs
using System;
using System.Globalization;
using System.Web.Mvc;
namespace RTVSApiFD.Logs
{
///
/// API过滤器
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class ApiTrackerFilter : System.Web.Mvc.ActionFilterAttribute, System.Web.Mvc.IActionFilter, System.Web.Mvc.IResultFilter, System.Web.Http.Filters.IFilter
{
private readonly string key = "_thisOnApiActionMonitorLog_";
#region Action时间监控
///
/// OnActionExecuting
///
///
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
MonitorLog monLog = new MonitorLog();
monLog.ExecuteStartTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ffff", DateTimeFormatInfo.InvariantInfo));
monLog.ControllerName = filterContext.RouteData.Values["controller"] as string;
monLog.ActionName = filterContext.RouteData.Values["action"] as string;
filterContext.Controller.ViewData[this.key] = monLog;
}
///
/// OnActionExecuted
///
///
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
MonitorLog monLog = filterContext.Controller.ViewData[this.key] as MonitorLog;
monLog.ExecuteEndTime = DateTime.Now;
monLog.FormCollections = filterContext.HttpContext.Request.Form;//form表单提交的数据
monLog.QueryCollections = filterContext.HttpContext.Request.QueryString;//Url 参数
LoggerHelper.Monitor(monLog.GetLogInfo());
}
#endregion
#region View 视图生成时间监控
///
/// OnResultExecuting
///
///
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
MonitorLog monLog = filterContext.Controller.ViewData[this.key] as MonitorLog;
monLog.ExecuteStartTime = DateTime.Now;
}
///
/// OnResultExecuted
///
///
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
MonitorLog monLog = filterContext.Controller.ViewData[this.key] as MonitorLog;
monLog.ExecuteEndTime = DateTime.Now;
LoggerHelper.Monitor(monLog.GetLogInfo(MonitorLog.MonitorType.View));
filterContext.Controller.ViewData.Remove(this.key);
}
#endregion
#region 错误日志
///
/// OnException
///
///
public void OnException(ExceptionContext filterContext)
{
if (!filterContext.ExceptionHandled)
{
string controllerName = string.Format("{0}Controller", filterContext.RouteData.Values["controller"] as string);
string actionName = filterContext.RouteData.Values["action"] as string;
string errorMsg = string.Format("在执行 controller[{0}] 的 action[{1}] 时产生异常", controllerName, actionName);
LoggerHelper.Error(errorMsg, filterContext.Exception);
}
}
///
/// OnAuthorization
///
///
public void OnAuthorization(AuthorizationContext filterContext)
{
这个方法是在Action执行之前调用
//var user = filterContext.HttpContext.Session["userName"];
//if (user == null)
//{
// //filterConetext.HttpContext.Response.Redirect("/Login/index");
// var url = new UrlHelper(filterContext.RequestContext);
// var urls = url.Action("Index", "Login");
// filterContext.Result = new RedirectResult(urls);
//}
}
#endregion
}
}
在Global.asax文件中添加读取日志的配置
using JT1078Server;
using log4net.Config;
using RedisHelp;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace RTVSApiFD
{
///
/// 全局启动类
///
public class WebApiApplication : System.Web.HttpApplication
{
///
/// Redis帮助类初始化
///
public static RedisHelper RedisHelper = new RedisHelper();
///
/// 音视频服务
///
public static Task TaskService = new Task();
///
/// 启动web程序
///
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//应用程序启动时,自动加载配置log4Net
log4net.Config.XmlConfigurator.Configure();
GlobalConfiguration.Configuration.Filters.Add(new Logs.ApiTrackerFilter());
}
}
}
此时还需要修改FilterConfig类,添加注册过滤器:
using System.Web;
using System.Web.Mvc;
namespace RTVSApiFD
{
///
/// 过滤器配置
///
public class FilterConfig
{
///
/// 注册全局过滤器
///
///
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//API日志
filters.Add(new Logs.ApiTrackerFilter());
//监控日志
filters.Add(new Logs.TrackerFilter());
filters.Add(new HandleErrorAttribute());
}
}
}
修改web.config文件加入日志配置:
编写一个简单的API测试,下面是API的一个方法:
[HttpPost]
public Result MultiSIMAlarmForJsonParam(FileSourceMultiRequest fileSourceMultiRequest)
{
Result result = null;
try
{
if (fileSourceMultiRequest != null)
{
LoggerHelper.Monitor("MultiSIMAlarmForJsonParam:" + fileSourceMultiRequest.ToJson());
LoggerHelper.Info("MultiSIMAlarmForJsonParam:" + fileSourceMultiRequest.ToJson());
List list = cache.QueryMulti(fileSourceMultiRequest.Sims, fileSourceMultiRequest.Channel, fileSourceMultiRequest.Alarms, fileSourceMultiRequest.StorageType, fileSourceMultiRequest.StreamType, fileSourceMultiRequest.StartTime.DateTimeToUNIX_long(), fileSourceMultiRequest.EndTime.DateTimeToUNIX_long(),fileSourceMultiRequest.DataType);
LoggerHelper.Info("MultiSIMAlarmForJsonParam:list.size=" + (list == null ? 0 : list.Count));
if (list != null)
{
result = new Result(1, "查询成功!", list);
}
else
{
result = new Result(0, "没有查询到结果!", new List());
}
LoggerHelper.Info("Result=" + result.ToJson());
}
}
catch (Exception ex)
{
result = new Result(2, "异常:" + ex.Message, new List());
LoggerHelper.Error("MultiSIMAlarmForJsonParam异常:" + result.ToJson());
}
return result;
}
查看日志(运行的时候回自动创建日志路径):
自此,日志就配置完成了!
参考文章:https://www.cnblogs.com/huanghzm/p/4754890.html