现在的企业级开发项目,特别是网站一般都会用到log功能,想想大部分会用Enterprise Logging Application Block 的功能 或者自己写一个组件,记录系统日志事件,更好的跟踪了解系统运行情况, 现用ASP.NET MVC 的过滤属性实现log功能!
ASP.NET MVC的filter 是一个属性,可以应用到controller 后者action.当Controller或者action method 被调用时,ASP.NET MVC的filter在调用执行前后会被触发。 先看下当Control 里面的action 被调用时的利用继承,自定义类log的效果图:
要实现上面的效果,现自定义一个类LogMessageAttribute,LogMessageAttribute继承接口IActionFilter ,IResultFilter,也可以选择性的继承重写类FilterAttribute。
IActionFilter interface 定义为:
public interface IActionFilter
{
// Methods
void OnActionExecuted(ActionExecutedContext filterContext);
void OnActionExecuting(ActionExecutingContext filterContext);
}
OnActionExecuting :在Controller 里面的action method 调用之前运行
OnActionExecuted:在Controller 里面的action method 调用之后运行,但是在IResultFilter接口的OnResultExecuting方法执行之前
IResultFilter interface定义为:
public interface IResultFilter
{
// Methods
void OnResultExecuted(ResultExecutedContext filterContext);
void OnResultExecuting(ResultExecutingContext filterContext);
}
OnResultExecuting:在Controller 里面的action method调用处理玩前执行.
OnResultExecuted:在Controller 里面的action method调用处理玩后执行.
接下来是重头戏:LogMessageAttribute自定义类
[AttributeUsage(AttributeTargets.Class |AttributeTargets.Method ,Inherited=true ,AllowMultiple=true )]
public class LogMessageAttribute:FilterAttribute,IActionFilter,IResultFilter
{
/// <summary>
/// <param name="LogName ">日志文件路径</para>
/// </summary>
public string LogName {
get;
set;
}
/// <summary>
/// 记录时间,系统版本,当前线程ID 等记录
/// </summary>
/// <param name="controller"></param>
/// <param name="action"></param>
/// <param name="message"></param>
public void LogMessage(string controller, string action, string message)
{
if (!string.IsNullOrEmpty(LogName))
{
TextWriter writer = new StreamWriter(LogName, true);
writer.WriteLine("################# Begin #################");
writer.WriteLine("Time:[{0}]",DateTime.Now.ToString("yyyy-MM-dd- hh:mm:ss"));
writer.WriteLine("Controller:{0}",controller);
writer.WriteLine("Action:{0}",action);
writer.WriteLine("Message:{0}",message);
writer.WriteLine("Operating System version is:{0}",System.Environment.OSVersion.Version.ToString());
writer.WriteLine("Current Thread ID is:{0}",AppDomain.GetCurrentThreadId());
writer.WriteLine("############### Over ###############");
writer.Close();
}
}
public void OnActionExecuting(ActionExecutingContext filterContext)