根据记录器实例动态设置Nlog日志级别ASP.Net Core 2.x [英] Dynamically Set Nlog Log Level per Logger Instance ASP.Net Core 2.x

查看:116
本文介绍了根据记录器实例动态设置Nlog日志级别ASP.Net Core 2.x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:要动态选择我要详细记录(不同日志级别)的HTTP请求.

Objective: To dynamically select which HTTP request I want verbose logging (different log level).

概述:我有一个正在运行的ASP.Net core 2.1 Web服务器,并且已经投入生产,如果我需要调试问题,我希望能够更改日志级别.我已经找到了如何全局更改日志级别;但是,更改日志级别是永久性的……也就是说,每次调用控制器后都不会重置.

Overview: I have a ASP.Net core 2.1 web server running and once in production, if I need to debug an issue I want to be able to change the log level. I have found how to globally change the log level; however, changing the log level is persistent... aka, does not reset after each call to my controller.

    [HttpGet]
    public async Task<IEnumerable<string>> Get()
    {
        this.Logger.LogTrace("This should NOT get logged");
        SetMinLogLevel(LogLevel.Trace);
        this.Logger.LogTrace("This should be logged");

        return new string[] { "value1", "value2" };
    }

   public static void SetMinLogLevel(LogLevel NewLogLevel)
    {
        foreach (var rule in LogManager.Configuration.LoggingRules)
        {
            rule.EnableLoggingForLevel(NewLogLevel);
        }

        //Call to update existing Loggers created with GetLogger() or 
        //GetCurrentClassLogger()
        LogManager.ReconfigExistingLoggers();
    }

我希望请求者能够在其HTTP请求(标头或cookie)中设置一个标志,以使每个请求的日志记录级别更加详细.这样,我就不会将请求者的详细日志淹没在我的日志中.

I want the requester to be able set a flag in their HTTP request (header or cookie) to enable a more verbose level of logging per request. That way I do not flood my logs with detailed logs from their requester.

问题:如何动态设置每个记录器实例的日志级别?(我相信这是正确的措辞)

Question: How to I dynamically set the Log Level per logger instance? (I believe that is the correct wording)

我当前正在使用NLog软件包4.5.

I am currently using NLog package 4.5.

推荐答案

NLog 4.6.7允许您在日志规则过滤器中将布局用于 minLevel / maxLevel

NLog 4.6.7 allows you to use Layouts in loggingrules filters for minLevel / maxLevel

您可以拥有一个具有默认日志级别的NLog-Config-Variable,然后在您的Web应用程序上创建一个隐藏方法,以修改NLog-Config-Variable并调用 ReconfigExistingLoggers().

You can have a NLog-Config-Variable with default loglevel, and then create a hidden method on your web-app that modifies the NLog-Config-Variable and calls ReconfigExistingLoggers().

然后设置一个计时器,该计时器在30秒后将NLog-Config-Variable还原为其原始值.并且还调用 ReconfigExistingLoggers().

Then setup a Timer that restores that NLog-Config-Variable to its orignal value after 30 secs. And also calls ReconfigExistingLoggers().

另请参阅: https://github.com/NLog/NLog/wiki/Filtering-log-messages#semi-dynamic-routing-rules

这篇关于根据记录器实例动态设置Nlog日志级别ASP.Net Core 2.x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆