NLog-仅在调试时记录 [英] NLog - Only log while debugging
问题描述
进行以下简单的NLog示例配置:
Take this simple NLog example configuration:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" xsi:type="File" fileName="file.txt" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logfile" />
</rules>
</nlog>
如何将其设置为仅在调试时记录日志,而不是在生产环境中运行时记录日志?
How can this be set up to only log while debugging, and not when run in production?
使事情更具挑战性:我的NLog配置文件是集中的,并在所有应用程序/服务/站点上共享.因此,我想避免更改每个项目,而只需修改配置文件.
To make things a bit more challenging: My NLog configuration files are centralized, shared over all applications/services/sites. So I would like to avoid altering every single project and just modify the config files.
推荐答案
我在这里看到了三种解决方案.
I see three solutions here.
1)使用配置文件及其转换一个>.目前,Web应用程序支持转换(我在谈论VS2012).对于桌面应用程序,您需要安装其他扩展名.
1) Using config file and its transformations. For the moment the transformations are supported for web applications (Im talking about VS2012). For desktop app you need to install additional extension.
2)使用两个目标,一个用于开发(我假设您是debug = development),第二个用于生产.在运行时,您需要通过删除另一个来保留实际的一个.
2) Use two targets, one for development (I assume debugging=development in your case) and the second for production. At runtime you need to leave actual one by removing the other.
更新
3)如果您不想更改项目,则可以应用自定义条件到记录器,具体取决于自定义布局渲染器(请参见如何制作自定义布局渲染器的示例).在您的情况下,布局渲染器应返回正在执行的程序集的当前Build Configuration(调试或发布).结果,条件将如下所示:
3) If you don't want to alter the projects it is possible to apply custom conditions to the logger depending on custom Layout Renderer (see example of how to make a custom layout renderer). In your case the layout renderer should return current Build Configuration (Debug or Release) of executing assembly. As a result the condition will look like this:
<rules>
<logger name="*" writeTo="logfile">
<filters>
<when condition="equals('${buildConfiguration}','Release')" action="Ignore" />
</filters>
</logger>
</rules>
其中 $ {buildConfiguration} 是您的自定义布局渲染器.
where ${buildConfiguration} is your custom layout renderer.
PS 而且不要忘记放这个
<extensions>
<add assembly="NameOfMyAssemblyThatContainsMyLayoutRenderer" />
</extensions>
到nlog.config,以便NLog知道布局渲染器.
to the nlog.config so NLog knows about the layout renderer.
这篇关于NLog-仅在调试时记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!