【问题标题】:ASP.NET Core 5.0 nlog implementation not workingASP.NET Core 5.0 nlog 实现不起作用
【发布时间】:2021-12-11 18:38:39
【问题描述】:

我正在开发一个我想记录异常但它不起作用的应用程序。我想记录的错误基本上是关于 validateToken 我想知道我得到了什么异常。这是我的实现,我添加了用于 nLog 的所有代码。

程序.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args).UseNLog()
            .ConfigureLogging((hostingContext, logging) =>
            {
                // Remove all the default logging providers
                logging.ClearProviders();
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddNLog().SetMinimumLevel(LogLevel.Error);
            })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

这是nlog.config文件的截图:

appSetting.json 设置文件:

"NLogConnection": {
    "DbProvider": "sqlserver",
    "DbHost": "SQL5103.site4now.net",
    "Database": "db_a7b629_testdatabase",
    "User": "db_a7b629_testdatabase_admin",
    "Password": "Ad*******"
  },

这是我要记录异常的地方

public class UserProfileInfo : IUserProfileInfo
{
    private readonly IHttpNetClientService _apiService;
    protected readonly IOptions<AppSettingDTO.AppSettingDTO> _appSetting;
    private readonly ILogger<UserProfileInfo> _logger;

    public UserProfileInfo(ILogger<UserProfileInfo> logger, IHttpNetClientService HttpClient, IOptions<AppSettingDTO.AppSettingDTO> AppSettings)
    {
        _apiService = HttpClient;
        _appSetting = AppSettings;
        this._logger = logger;
    }
    
    public bool ValidateToken(string token)
    {
        var tokenHandler = new JwtSecurityTokenHandler();

        try
        {
            tokenHandler.ValidateToken(token, new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                ValidateIssuer = true,
                ValidateAudience = false,
                ValidateLifetime = true,
                ValidIssuer = _appSetting.Value.Jwt.Issuer,
                ValidAudience = _appSetting.Value.Jwt.Audience,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSetting.Value.Jwt.Key)),
                ClockSkew = TimeSpan.Zero
            }, out SecurityToken validatedToken);
        }
        catch (Exception ex)
        {
            // this where I want to log an exception but it is not working .. and always log me an error in the txt file generated in c:\temp folder 
            this._logger.LogError($"---- Token Error ----", ex.Message);
            return false;
        }

        return true;
    }
}

txt 文件中的错误日志

2021-10-26 13:38:28.8797 Info Message Template Auto Format enabled
2021-10-26 13:38:28.8797 Info Loading assembly: NLog.Web.AspNetCore
2021-10-26 13:38:28.9069 Info Adding target DatabaseTarget(Name=database)
2021-10-26 13:38:28.9335 Info Validating config: TargetNames=database, ConfigItems=33, FilePath=C:\Kamran  Don't Delete\SAUFIK\Project Files\GMD\GMDAPI\GMDApi\bin\Debug\net5.0\NLog.config
2021-10-26 13:38:28.9582 Info Configuration initialized.
2021-10-26 13:38:28.9582 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.7.9.12899. Product version: 4.7.9+e8712e62842e2d74d60fdf37cf74d743750e5ca2. GlobalAssemblyCache: False

当出现异常但数据库中没有任何内容时,上面的错误是登录到默认的 txt 文件,我不知道可能是我的 UserProfileinfo 类有问题。

【问题讨论】:

    标签: asp.net-core asp.net-web-api nlog


    【解决方案1】:

    记录规则决定记录器输出应该写在哪里。您的日志记录规则说只有名称为 database 的记录器才应该写入 database-target:

    <rules>
       <logger name="database" minlevel="error" writeto="database" />
    </rules>
    

    但在您的代码中,您使用的是ILogger&lt;UserProfileInfo&gt;,它的记录器名称将基于typeof(UserProfileInfo).Name

    如果您只想让所有错误都独立于记录器名称,那么只需使用*-wildcard:

    <rules>
       <logger name="*" minlevel="error" writeto="database" />
    </rules>
    

    另请参阅:https://github.com/NLog/NLog/wiki/Tutorial

    另见:https://github.com/nlog/NLog/wiki/Configuration-file#rules

    另见:https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-GetCurrentClassLogger-and-Microsoft-ILogger

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2021-12-17
      • 2021-10-30
      • 1970-01-01
      • 2019-02-24
      相关资源
      最近更新 更多