【发布时间】: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