.NET NLog 详解(四) - filter
我们将版本向前切换到20051025,这期的关注点是filter。我们在使用日志的时候可能希望加上一些过滤器,在满足某些特定条件的时候才输出。举个简单的使用方式如下:
<nlog>
<targets><target name='debug' type='Debug' layout='${basedir} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' appendTo='debug'>
<filters>
<whenContains layout='${message}' substring='zzz' action='Ignore' />
</filters>
</logger>
</rules>
</nlog>
初始化
FilterFactory负责初始化程序集中的Filter
public sealed class FilterFactory
{
private static TypeDictionary _filters = new TypeDictionary();
static FilterFactory()
{
foreach (Assembly a in ExtensionUtils.GetExtensionAssemblies())
{
AddFiltersFromAssembly(a, "");
}
}
反射初始化的方式和上篇的LayoutRender没有差别
public static void AddFiltersFromAssembly(Assembly theAssembly, string prefix)
{
try
{
InternalLogger.Debug("AddFiltersFromAssembly('{0}')", theAssembly.FullName);
foreach (Type t in theAssembly.GetTypes())
{
FilterAttribute[]attributes = (FilterAttribute[])t.GetCustomAttributes(typeof(FilterAttribute), false);
if (attributes != null)
{
foreach (FilterAttribute attr in attributes)
{
AddFilter(prefix + attr.Name, t);
}
}
}
}
catch (Exception ex)
{
InternalLogger.Error("Failed to add filters from '" + theAssembly.FullName + "': {0}", ex);
}
}
加载配置文件中的Filter
只是简单的从初始化好的_filters字典里面取出即可,如果发现没有,就会尝试反射创建
执行
还是在LoggerImpl
的Write
方法中以链式的方式嵌入
for (TargetWithFilterChain awf = targets; awf != null; awf = awf.Next)
{
Target app = awf.Target;
try
{
FilterCollection filterChain = awf.FilterChain;
FilterResult result = FilterResult.Neutral;
for (int i = 0; i < filterChain.Count; ++i)
{
Filter f = filterChain[i];
result = f.Check(logMessage);
if (result != FilterResult.Neutral)
break;
}
if (result == FilterResult.Ignore)
{
if (InternalLogger.IsDebugEnabled)
{
InternalLogger.Debug("{0}.{1} Rejecting message because of a filter.", logger.Name, level);
}
continue;
}
}
这里可以看到,如果filter 的result 是Ignore
,该Message的Target就不需要再输出了。
TargetWithFilterChain
是包装Target的关键类型:
internal class TargetWithFilterChain
{
private Target _target;
private FilterCollection _filterChain;
private TargetWithFilterChain _next;
public TargetWithFilterChain(Target a, FilterCollection filterChain)
{
_target = a;
_filterChain = filterChain;
}
这个类型的实现很简单,就是将Target和FilterChain打包放在一起。
InternalLogger
这里值得注意的细节是InternalLogger
记录了内部一些详情,当我们需要的时候直接开启InternalLogger
调试日志组件的工作过程。
我们对于InternalLogger
的要求是不要影响正常程序的运行过程,仅仅在调试日志组件功能的时候使用,因此里面的代码牺牲异常也保证安全。
static InternalLogger()
{
try
{
switch (ConfigurationSettings.AppSettings["nlog.internalLogToConsole"].ToLower())
{
case "false":
LogToConsole = false;
break;
case "true":
LogToConsole = true;
break;
default:
if (EnvironmentHelper.GetSafeEnvironmentVariable("NLOG_INTERNAL_LOG_TO_CONSOLE") != null)
{
LogToConsole = true;
}
break;
}
string levelString = ConfigurationSettings.AppSettings["nlog.internalLogLevel"];
if (levelString == null || levelString.Length == 0)
levelString = EnvironmentHelper.GetSafeEnvironmentVariable("NLOG_INTERNAL_LOG_LEVEL");
if (levelString != null && levelString.Length > 0)
LogLevel = LogLevel.FromString(EnvironmentHelper.GetSafeEnvironmentVariable("NLOG_INTERNAL_LOG_LEVEL"));
LogFile = ConfigurationSettings.AppSettings["nlog.internalLogFile"];
if (LogFile == null)
LogFile = EnvironmentHelper.GetSafeEnvironmentVariable("NLOG_INTERNAL_LOG_FILE");
Info("NLog internal logger initialized.");
}
catch {}
}
可以看到InternalLogger
的开启不依赖于原来的配置文件结构,默认不输出,以及取环境变量处理的也非常小心。
public static string GetSafeEnvironmentVariable(string name)
{
try
{
string s = Environment.GetEnvironmentVariable(name);
if (s == "")
return null;
else
return s;
}
catch (SecurityException)
{
return "";
}
}
.NET NLog 详解(四) - filter的更多相关文章
- logback -- 配置详解 -- 四 -- <filter>
附: logback.xml实例 logback -- 配置详解 -- 一 -- <configuration>及子节点 logback -- 配置详解 -- 二 -- <appen ...
- iptables详解之filter
iptables详解之filter iptables令很多小伙伴脑阔疼,下面我们来说说如何使用iptables. 一.iptables格式 1.1.iptables 帮助 通过iptables --h ...
- .NET DLL 保护措施详解(四)各操作系统运行情况
我准备了WEB应用程序及WinForm应用程序,分别在WIN SERVER 2012/2008/2003.Win7/10上实测,以下为实测结果截图: 2012 2008 2003 WIN7 WIN10 ...
- pika详解(四) channel 通道
pika详解(四) channel 通道 本文链接:https://blog.csdn.net/comprel/article/details/94662394 版权 channel通道 通道 ...
- logback配置详解3<filter>
logback 常用配置详解(三) <filter> <filter>: 过滤器,执行一个过滤器会有返回个枚举值,即DENY,NEUTRAL,ACCEPT其中之一.返回DENY ...
- View绘制详解(四),谝一谝layout过程
上篇博客我们介绍了View的测量过程,这只是View显示过程的第一步,第二步就是layout了,这个我们一般译作布局,其实就是在View测量完成之后根据View的大小,将其一个一个摆放在ViewGro ...
- Servlet和Filter的url匹配以及url-pattern详解 及 filter 循环问题的解决
Servlet和filter是J2EE开发中常用的技术,使用方便,配置简单,老少皆宜.估计大多数朋友都是直接配置用,也没有关心过具体的细节,今天遇到一个问题,上网查了servlet的规范才发现,ser ...
- 详解Kalman Filter
中心思想 现有: 已知上一刻状态,预测下一刻状态的方法,能得到一个"预测值".(当然这个估计值是有误差的) 某种测量方法,可以测量出系统状态的"测量值".(当然 ...
- C++11 并发指南六(atomic 类型详解四 C 风格原子操作介绍)
前面三篇文章<C++11 并发指南六(atomic 类型详解一 atomic_flag 介绍)>.<C++11 并发指南六( <atomic> 类型详解二 std::at ...
随机推荐
- sql server2008 获取动态sql的变量值
--通过SQL 字符串 查询 获取查出的值sp_executesql declare @QuerySql nvarchar(500),@uid int,@Ucode varchar(100);set ...
- Tomcat部署Web应用的两种方式
WEB工程目录结构 部署方式一:此种方式部署,jsp页面修改后,不能动态更新,需要重新部署才能看到效果.不过可以配置动态更新实现. 部署方式二:此种方式部署,jsp修改后,直接在页面可以看到效果.(因 ...
- HTK学习1:安装编译
选自:http://www.cnblogs.com/mingzhao810/archive/2012/08/03/2617674.html HTK(HMM Toolkit)一款基于hmm模型的语音处理 ...
- (转) Docker swarm - 使用体验 1+2
背景 凭借敏捷开发部署理念的推行,相信对于很多人来说docker这项容器技术已经并不陌生,Docker 1.12引擎发布了快两个月,新引擎中包含了许多特性.诸如: Swarm模式,容器集群的健康检查, ...
- springMVC 访问404
问题:404 但是其他的controller可以访问!!!
- HBase集成Zookeeper集群部署
大数据集群为了保证故障转移,一般通过zookeeper来整体协调管理,当节点数大于等于6个时推荐使用,接下来描述一下Hbase集群部署在zookeeper上的过程: 安装Hbase之前首先系统应该做通 ...
- Java for LeetCode 231 Power of Two
public boolean isPowerOfTwo(int n) { if(n<1) return false; while(n!=1){ if(n%2!=0) return false; ...
- FileUpload控件使用初步
FileUpload控件使用初步 FileUpload控件使用初步: 1.实现文件上传 protected void btnSubmit_click(object sender, EventArg ...
- JS 基本语句
1.循环中必备的条件: 初始值 循环条件 状态改变 循环体 for(初始值 循环条件 状态改变) { 循环体 } for(var i=0;i<100;i++ ...
- 【leetcode】Wildcard Matching(hard) ★ 大神太牛了
Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. ...