需求1:在每次方法进来的时候和出去的时候,记录方法日志
需求2:有的方法需要日志有的方法不需要日志,此处用特性来解决
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
aec = filterContext;
//获得容器名字
var controllerName = aec.ActionDescriptor.ControllerDescriptor.ControllerName;
//获得方法名
var actionName1 = aec.ActionDescriptor.ActionName;
//获得Controller类型
Type t = aec.ActionDescriptor.ControllerDescriptor.ControllerType;
//是否有该特性,含有此特性直接忽略
bool hasAttribute = IsThatAttribute(actionName1, t);
if (!hasAttribute)
{
foreach (var item in aec.ActionParameters.Values)
{
LogManager2.InfoFormat("{0}|{1}|InputPara:{2}", controllerName, actionName1, JsonConvert.SerializeObject(item));
}
}
var actionName = $"{controllerName}/{actionName1} ";
}
/// <summary>
/// 判断此方法是否有特性
/// </summary>
/// <typeparam name="T">特性名字</typeparam>
/// <param name="actionname">方法名</param>
/// <param name="t">类</param>
/// <returns></returns>
public bool IsThatAttribute<T>(string actionname, Type t)
{
int length = t.GetMethod(actionname).GetCustomAttributes(typeof(T), true).Length;
return length > 0 ? true : false;
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
//获得容器名字
var controllerName = aec.ActionDescriptor.ControllerDescriptor.ControllerName;
//获得方法名
var actionName1 = aec.ActionDescriptor.ActionName;
//获得Controller类型
Type t = aec.ActionDescriptor.ControllerDescriptor.ControllerType;
//是否有该特性,含有此特性直接忽略
bool hasAttribute = IsThatAttribute<Nolog4Attribute>(actionName1, t);
if (!hasAttribute)
{
LogManager2.InfoFormat("{0}|{1}|OuputPara:{2}", controllerName, actionName1, JsonConvert.SerializeObject(filterContext.Result));
}
var actionName = $"{controllerName}/{actionName1} ";
}
/// <summary>
/// 使用在不需要记录日志的方法上
/// </summary>
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = true)]
public class Nolog4Attribute : Attribute //类名是特性的名称
{
public Nolog4Attribute()
{
}
}