我有 ASP.NET Core 1.1 应用程序,并且正在使用 Serilog 进行日志记录。我想通过保留 DTO 对象的结构来记录它。
所以如果我直接使用Serilog.Log
来记录DTO,如下所示
Serilog.Log.Information("Processing {@DTO}", dto);
然后 Serilog 序列化 DTO 并按预期记录它。
但是我将 Microsoft.Extension.Logging.ILogger
注入(inject) Controller 。我认为它将使用配置的记录器进行日志记录,并且会在日志记录时序列化对象,但事实并非如此。它只记录对象的类型名称。
public class HomeController
{
private readonly Microsoft.Extensions.Logging.ILogger _logger = null
public HomeController(Microsoft.Extensions.Logging.ILogger logger)
{
_logger = logger;
}
public asyc IActionResult Index()
{
var dto = GetDTO();
//did not work
_logger.LogInformation("DTO {dto}",dto);
//did not work
_logger.LogInformation("DTO {@dto}",dto);
//worked when i use serilog directly
Serilog.Log.Information("DTO {@dto}",dto);
//did not work
Serilog.Log.Information("DTO {dto}",dto);
}
}
Startup.cs
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.CreateLogger();
}
appsettings.json
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Information"
}
},
"Serilog": {
"WriteTo": [
{
"Name": "ColoredConsole"
}
]
},
最佳答案
我找到了。我的错误
在配置方法中的Startup.cs
中,我只为非开发环境添加了Serilog
,并且我正在使用 ASPNETCORE_ENVIRONMENT = Development 进行本地测试。
if(!env.IsDevelopment())
{
loggerFactory.AddSerilog();
}
我删除了 if 条件并且它起作用了。
所以 _logger.LogInformation("DTO {@dto}",dto);
有效
关于c# - .Net Core 1.1 在记录时不序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54834986/