我正在运行此存储库中的代码并从 Book.API 生成错误,我收到如下错误页面:

请求 ID 为 |574e8e13-4e9d31fed64d4793。
当我查看文件中的日志条目时,我看到:
{
"Timestamp": "2021-01-25T18:07:24.6565993-06:00",
"Level": "Fatal",
"MessageTemplate": "BADNESS!!! Cannot open database \"Demo_EffectiveLogging\" requested by the login. The login failed.\r\nLogin failed for user 'TCA-PRECISION\\terry.aney'. -- {ErrorId}.",
"Exception": "System.Data.SqlClient.SqlException (0x80131904): Cannot open database \"Demo_EffectiveLogging\" requested by the login. The login failed.\r\nLogin failed for user 'TCA-PRECISION\\terry.aney'.\r\n at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken)\r\n at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, …Run Code Online (Sandbox Code Playgroud) 我有一个系统,我想制作自定义日志来为每个用户创建单独的文件夹。现在,我在 NLog.Logger 中将其制作为自定义文件目标
public static LogFactory ConfigureCustomNLog(string userName)
{
var target = new FileTarget();
target.Name = "fileLog";
target.FileName = $"${{basedir}}/log" + $"/{userName}/{userName}" + "${shortdate}.log";
target.Layout =
"${longdate}|${uppercase:${level}} ${logger}|${message} ${exception:format=ToString,StackTrace}";
var config = ConfigureNLog("NLog.Config").Configuration;
config.RemoveTarget("fileLog");
config.AddTarget(target.Name, target);
var rule = new LoggingRule(userName, LogLevel.Debug, target);
config.LoggingRules.Add(rule);
LogManager.Configuration = config;
return LogManager.LogFactory;
}
Run Code Online (Sandbox Code Playgroud)
一切工作正常,但我想使用 Microsoft.Extensions.ILogger。如何将 NLog.Logger 导入到 ILogger?或者如何为 ILogger 进行自定义配置?
我有一个 C# .NET Core Azure Function App,并且使用 ILogger 将日志发送到 Application Insights。到目前为止,这运作良好。
函数头:
public static void Run([TimerTrigger("0 30 * * * *")] TimerInfo myTimer, ILogger log, ExecutionContext context)
ILogger的使用:
log.LogInformation($"MyFunction trigger function executed at: {DateTime.Now}");
在 App Insights 中,我看到日志包含默认信息,例如它来自哪个 Function App,以及message包含上述字符串的日志。
但是,现在我想记录自定义日志。我有一个IEnumerable<IDictionary<string, string>>,我希望列表中的每个字典元素都是一个单独的日志。理想情况下,我可以有一个日志,其中每个字段都是字典中的键,其值是相应的值。或者,我可以在日志中使用某种 customDimensions 字段,该字段将是一个包含列表中 1 个字典中的所有键值对的对象。
目的是使日志在 Kusto 中易于查询。我想避免在 App Insights 中查询它们时必须解析它们。
笔记:
我查看了许多其他类似的帖子,但似乎没有一个得到完整的回答。
c# azure-application-insights azure-functions ilogger appinsights
有几个相互调用的持久函数。 主编排 -> 子编排 -> Activity -> Helper 异步方法
每个函数都有 ILogger 依赖性,并在函数开始和函数结束时登录。由于某种原因,两个协调器都会重复“启动时”消息。(见图)活动没有这种效果。(见图)多次运行下面的示例 - 同一个故事。
我也确信整个过程已经被触发过一次。
这是协调器中的错误还是预期行为?
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
namespace Issues
{
public static class Log_Issue
{
[FunctionName("Main")]
public static async Task RunOrchestrator(
[OrchestrationTrigger] IDurableOrchestrationContext context,
ILogger log)
{
try
{
log.LogWarning("Main Start");
await context.CallSubOrchestratorAsync("Sub", null);
log.LogWarning("Main End");
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
[FunctionName("Sub")]
public static async Task RunSubOrchestrator(
[OrchestrationTrigger] IDurableOrchestrationContext context,
ILogger …Run Code Online (Sandbox Code Playgroud) 我已安装 Serilog 并配置为将日志事件数据写入 MS SQL Server for Azure Function 中的表。
系统日志和静态类本身写入的日志显示在表中,但是当我尝试使用 Extensions.Logging.ILogger 时,即使我可以在 ILogger 中看到 Serilog 提供程序,消息也不会显示在表中。
Startup.cs配置;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Azure.WebJobs.Hosting;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.MSSqlServer;
using Microsoft.Azure.WebJobs;
[assembly: FunctionsStartup(typeof(Rubix.FunctionApp.Startup))]
namespace Rubix.FunctionApp
{
public class Startup : IWebJobsStartup
{
public Startup()
{
var config = new ConfigurationBuilder()
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var logDbConnectionString = "connectionString";
var logTable = "LogEntry";
var columnOptions = new ColumnOptions()
{
AdditionalColumns = new Collection<SqlColumn>
{
new SqlColumn
{ColumnName = "Filter", …Run Code Online (Sandbox Code Playgroud) 我FunctionsStartup在 Azure Functions 项目中使用来设置 IoC 绑定。但是,ILogger<T>当我在 Azure 中运行它时,不会出现从注入创建的任何日志。
我用一个全新的示例项目创建了一个非常精简的版本来演示这一点......
https://github.com/dracan/AzureFunctionsLoggingIssue
这个输出是...
2020-04-03T20:20:35 Welcome, you are now connected to log-streaming service. The default timeout is 2 hours. Change the timeout with the App Setting SCM_LOGSTREAM_TIMEOUT (in seconds).
2020-04-03T20:20:54.643 [Information] Executing 'TestQueueTriggerFunction' (Reason='New queue message detected on 'myqueue'.', Id=2f13c4c7-8a35-4614-a768-1c3fecea8c31)
2020-04-03T20:20:54.654 [Information] Start of function (this log works)
2020-04-03T20:20:54.655 [Information] End of function (this log also works)
2020-04-03T20:20:54.655 [Information] Executed 'TestQueueTriggerFunction' (Succeeded, Id=2f13c4c7-8a35-4614-a768-1c3fecea8c31)
Run Code Online (Sandbox Code Playgroud)
请注意日志条目“此日志未出现!” inMyClass.DoSomething()没有出现。
ASP.NET CORE 3.1 Worker Service Application.
Packages
"Microsoft.EntityFrameworkCore.Design" Version="3.1.3"
PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.3"
PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="3.1.3"
PackageReference Include="Serilog.AspNetCore" Version="3.2.0"
PackageReference Include="Serilog.Extensions.Hosting" Version="3.0.0"
Run Code Online (Sandbox Code Playgroud)
Serilog 使用硬编码的 LoggerConfiguration 写入文件,但无法从从 appsettings.json 加载的配置中工作
这是应用程序代码
public static class Program
{
public static IConfigurationRoot Configuration { get; set; }
private static string _environmentName;
public static void Main(string[] args)
{
var hostBuilder = CreateHostBuilder(args).Build();
//Log.Logger = (Configuration["Logging:LogLevel:Default"] == "Debug")?
// new LoggerConfiguration()
// .MinimumLevel.Debug()
// .WriteTo.Console()
// .WriteTo.File(path: Path.Combine("C:/LogFiles", "OA-EmailService-.log"),
// rollingInterval: RollingInterval.Day, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(10))
// .CreateLogger() …Run Code Online (Sandbox Code Playgroud) 因此,我尝试使用依赖注入设置 ILogger,但遇到了一些麻烦。
在我的startup.cs文件中,我有一些看起来像这样的东西:
builder.Services.AddLogging();
Run Code Online (Sandbox Code Playgroud)
然后,我尝试将该记录器提供给我自己的类(它的作用就像 ILogger 库的包装器)
builder.Services.AddSingleton<LoggingWrapper>(s =>
{
return new LoggingWrapper(
s.GetService<ILoggerFactory>());
});
Run Code Online (Sandbox Code Playgroud)
因此,在我的 Azure 函数中,LoggingWrapper被注入内部,但它不会记录任何内容。每个函数附带的普通 ILogger 仍然可以工作,但我想知道为什么我的包装器没有记录任何内容。
Logging Wrapper 是一个类,它采用 ILogger 方法并使用它来创建自己的日志记录方法。例如loggingWrapper.logInformation("string"),有一个方法可以包装`ILogger.
我将其注入到我的其他类中,如下所示:s.GetService<ILoggerFactory>()
预先感谢您的所有帮助!
我在 Docker 容器内有一个 DotNet Core 应用程序,当我查看 ILogger 生成的日志时,我可以看到这些字符:
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[1]
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Run Code Online (Sandbox Code Playgroud)
你能帮我理解它们的意思吗?
当给出 null 时,它给出 Value 不能为 null。(参数“记录器”)错误。 即使给出模型实例,它仍然保持为空
public class MyController : Controller
{
public MyController(ILogger<MyController> logger)
{
logger.LogInformation("Log Testing");
}
public ActionResult List()
{
int Id = 5;
MyModel model = new MyModel(null);
model.GetItem(Id);
return View("List", model);
}
}
public class MyModal:BaseModel
{
private readonly ILogger<MyModal> _logger;
public MyModel(ILogger<MyModel> logger)
{
this._logger = logger;
}
public MyModel GetItem (Int Id)
{
try
{
//My Code
}
catch(Exception e){
_logger.LogError(e.Message);
}
}
}
Run Code Online (Sandbox Code Playgroud)
根据建议我编辑了我的问题
ilogger ×10
c# ×5
.net-core ×3
azure ×3
.net ×2
serilog ×2
appinsights ×1
asp.net-core ×1
file ×1
logging ×1
nlog ×1
razor-pages ×1