英文:
Not able to write logs to Azure Application Insights in Controller using Serilog
问题
你有一个.NET 6 Web API,尝试将日志写入Azure应用程序洞察。当我尝试在Program.cs中写入时,它有效。但是当我尝试在Controller操作方法中写入时,它不起作用。
以下是你的Program.cs部分:
public class Program
{
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
logger.Information("Hello, world!!!!!");
var builder = WebApplication.CreateBuilder(args);
}
}
以及Controller部分:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogInformation("Info");
_logger.LogTrace("Trace");
_logger.LogCritical("Critical");
_logger.LogDebug("Debug");
_logger.LogError("Error");
_logger.LogWarning("Warning");
Log.Information("Information!");
Log.Warning("Warning!");
Log.Error("Error!");
Log.Debug("Debug!");
Log.Logger.Error("Information!!");
Log.Logger.Warning("Warning!!");
Log.Logger.Error("Error!!");
Log.Logger.Debug("Debug!!");
Log.Logger.Warning("Warning!!");
}
}
你还提供了一个名为"Appsettings.json"的JSON文件,其中包含了日志配置信息。
请注意,你需要确保配置正确,并且在Controller中,你正在使用_logger
来记录日志。如果日志仍然不起作用,请检查应用程序洞察的配置和连接字符串。
英文:
I have a .net6 web API, I am trying to write logs to Azure application insights. It works when I try to write in Program.cs. But it's not writing when I am trying to write in the Controller action method.
public class Program
{
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
logger.Information("Hello, world!!!!!");
var builder = WebApplication.CreateBuilder(args);
Controller:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogInformation("Info");
_logger.LogTrace("Trace");
_logger.LogCritical("Critical");
_logger.LogDebug("Debug");
_logger.LogError("Error");
_logger.LogWarning("Warning");
Log.Information("Information!");
Log.Warning("Warning!");
Log.Error("Error!");
Log.Debug("Debug!");
Log.Logger.Error("Information!!");
Log.Logger.Warning("Warning!!");
Log.Logger.Error("Error!!");
Log.Logger.Debug("Debug!!");
Log.Logger.Warning("Warning!!");
Appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Serilog": {
"Using": [
"Serilog.Sinks.ApplicationInsights"
],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "ApplicationInsights",
"Args": {
"telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
}
}
],
"Enrich": [ "FromLogContext" ],
"Properties": {
"Application": "Sample"
}
}
}
I have set my connection string in the environment variable.
These are the Nuget packages along with the versions.
Azure app insights
答案1
得分: 1
以下是您提供的翻译:
-
正如您提到的,即使我在Visual Studio环境变量中设置了“Application Insights Connection String”。
-
最初,使用您的代码,我只能记录来自“Program.cs”文件的消息。
-
在“Program.cs”中进行了一些更改后,我才能看到来自“Controller”的消息。
“Progarm.cs”文件:
using Serilog;
using Serilog.Sinks.ApplicationInsights.TelemetryConverters;
var ConnStr = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING");
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.WriteTo.ApplicationInsights(ConnStr, new TraceTelemetryConverter())
.CreateLogger();
logger.Information("Hello, world ");
var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddSerilog(logger);
var app = builder.Build();
“Program.cs”中的消息:
“Controller”中的消息:
“Controller.cs”:
using Microsoft.AspNetCore.Mvc;
using Serilog;
namespace SerilogInsights.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogInformation("Info..");
_logger.LogTrace("Trace from Controller");
_logger.LogCritical("Critical trace");
_logger.LogDebug("Debug message logs");
_logger.LogError("Error message");
_logger.LogWarning("Warning message");
Log.Information("Information!");
Log.Warning("Warning!");
Log.Error("Error!");
Log.Debug("Debug!...");
Log.Logger.Error("Information!! ...");
Log.Logger.Warning("Warning!!");
Log.Logger.Error("Error!!");
Log.Logger.Debug("Debug!!");
Log.Logger.Warning("Warning!!");
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
我的.csproj
文件:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.AspNetCore" Version="6.1.0" />
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
</Project>
英文:
- As you mentioned, Even I have set
Application Insights Connection String
in Visual Studio Environment Variable.
- Initially with your code Iam able to log only the messages from
Program.cs
file.
- After making few changes in
Program.cs
only Iam able to see the messages fromController
.
Progarm.cs
file:
using Serilog;
using Serilog.Sinks.ApplicationInsights.TelemetryConverters;
var ConnStr = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING");
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.WriteTo.ApplicationInsights(ConnStr, new TraceTelemetryConverter())
.CreateLogger();
logger.Information("Hello, world ");
var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddSerilog(logger);
var app = builder.Build();
Message from Program.cs
:
Message from Controller
:
My Controller.cs
:
using Microsoft.AspNetCore.Mvc;
using Serilog;
namespace SerilogInsights.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogInformation("Info..");
_logger.LogTrace("Trace from Controller");
_logger.LogCritical("Critical trace");
_logger.LogDebug("Debug message logs");
_logger.LogError("Error message");
_logger.LogWarning("Warning message");
Log.Information("Information!");
Log.Warning("Warning!");
Log.Error("Error!");
Log.Debug("Debug!...");
Log.Logger.Error("Information!! ...");
Log.Logger.Warning("Warning!!");
Log.Logger.Error("Error!!");
Log.Logger.Debug("Debug!!");
Log.Logger.Warning("Warning!!");
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
My .csproj
file:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.AspNetCore" Version="6.1.0" />
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
</Project>
答案2
得分: 0
以下是您要的中文翻译:
似乎 Program.cs
中的代码没有正确配置 Serilog。
如果您按照 配置基础 - Serilog Wiki 的说明,您必须将 Serilog.Log
设置为日志记录器。
因此,请尝试将以下代码:
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
更改为:
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
这样,Log
方法将正常工作。但是,您必须使用 Log
类,并且不能使用 ILogger
注入,因为 Serilog 没有设置为“默认日志记录器”方法。
我建议使用 Serilog.AspNetCore 包,并按照 README 中的说明设置您的应用程序。
using Serilog;
// 为启动提供日志记录功能
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
try
{
Log.Information("启动 Web 应用程序");
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog();
// ...
var app = builder.Build();
// ...
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "应用程序意外终止");
}
finally
{
Log.CloseAndFlush();
}
希望这有助于您的代码配置。
英文:
It seems to me that the code in Program.cs
doesn't configure Serilog properly.
If you follow Configuration Basics - Serilog Wiki you must set Serilog.Log
to a logger.
So try to change
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
to
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
In this way Log
methods will work. But, you must use Log
class and couldn't use ILogger
injection, since Serilog is not set as "the default logger" method.
I suggest to use Serilog.AspNetCore package and setup your application as written in the README.
using Serilog;
// This provide logger functionality for startup
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
try
{
Log.Information("Starting web application");
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog();
// ...
var app = builder.Build();
// ...
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论