[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,
Inherited=true,AllowMultiple=true)]
public class LogAttribute :FilterAttribute,IActionFilter,IResultFilter
{
public string LogName { get; set; }
public void Log(string controller, string action, string msg)
{
if (!string.IsNullOrEmpty(LogName))
{
TextWriter writer = new StreamWriter(LogName, true);
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("Msg:{0}", msg);
writer.WriteLine("System:{0}", System.Environment.OSVersion.Version.ToString());
writer.WriteLine("ThreadID:{0}", AppDomain.GetCurrentThreadId());
writer.Close();
}
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
Log(filterContext.RouteData.Values["controller"].ToString(), filterContext.RouteData.Values["action"].ToString(), "Action Executing...");
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
Log(filterContext.RouteData.Values["controller"].ToString(), filterContext.RouteData.Values["action"].ToString(), "Action Executed.");
}
public void OnResultExecuting(ResultExecutingContext filterContext)
{
Log(filterContext.RouteData.Values["controller"].ToString(),
filterContext.RouteData.Values["action"].ToString(),
"Result executing...");
}
public void OnResultExecuted(ResultExecutedContext filterContext)
{
Log(filterContext.RouteData.Values["controller"].ToString(),
filterContext.RouteData.Values["action"].ToString(),
"Result executed");
}
}