我有一个使用Serilog和JSNLog进行客户端日志记录的.NET Core项目。如果我将JSON对象从客户端传递到服务器并使用Serilog进行记录,则记录的JSON对象为空。
非常奇怪 的事情是,如果我附加了调试器,则JSON记录正常。
例如:
调试时我得到:
[11:00:01 FTL] this works
[11:00:02 INF] Request finished in 342.1967ms 200 text/plain
[11:00:02 FTL] "testMessage": "this is an error"
[11:00:02 INF] Request finished in 374.7837ms 200 text/plain
当我得到Crtl + F5时:
[10:59:14 FTL] this works
[10:59:14 INF] Request finished in 253.3403ms 200 text/plain
[10:59:15 FTL] [[[]]]
[10:59:15 INF] Request finished in 267.2553ms 200 text/plain
我不确定问题是否与Serilog或JSNLog有关,但是我们将不胜感激。
我制作了一个非常简单的示例应用程序来复制它。使用默认的.NET Core Webapp
在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();
Log.Logger = new LoggerConfiguration()
.WriteTo.Console().CreateLogger();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddSerilog();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseJSNLog(new LoggingAdapter(loggerFactory));
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
在我的前端:
<script src="~/lib/jsnlog.js/jsnlog.min.js"></script>
<script>
JL().fatal({ testMessage: "this is an error" });
JL().fatal("this works");
</script>
答案 0 :(得分:3)
我有类似的问题。我看了一下JSNLog,似乎问题是在从日志消息中对对象进行去主体化时正在创建的JSON .NET对象的日志记录。
我做了以下解决方法:
Install-Package Destructurama.JsonNet
)然后我更改了Logger配置以包含解构:
Log.Logger = new LoggerConfiguration()
.Destructure.JsonNetTypes()
.WriteTo.Console()
.CreateLogger();
然后我创建了一个CustomLoggingAdapter
类,如下所示:
public class CustomLoggingAdapter: ILoggingAdapter
{
private ILoggerFactory _loggerFactory;
public CustomLoggingAdapter(ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
}
public void Log(FinalLogData finalLogData)
{
ILogger logger = _loggerFactory.CreateLogger(finalLogData.FinalLogger);
Object message = LogMessageHelpers.DeserializeIfPossible(finalLogData.FinalMessage);
switch (finalLogData.FinalLevel)
{
case Level.TRACE: logger.LogTrace("{@logMessage}", message); break;
case Level.DEBUG: logger.LogDebug("{@logMessage}", message); break;
case Level.INFO: logger.LogInformation("{@logMessage}", message); break;
case Level.WARN: logger.LogWarning("{@logMessage}", message); break;
case Level.ERROR: logger.LogError("{@logMessage}", message); break;
case Level.FATAL: logger.LogCritical("{@logMessage}", message); break;
}
}
}
并将日志更改为具有以下格式{@logMessage}
注意:可以在JSONLog GitHub repo中找到LogMessageHelpers.DeserializeIfPossible
然后我更改了JSNLog配置以接收我的CustomLoggingAdapter
,如下所示:
app.UseJSNLog(new CustomLoggingAdapter(loggerFactory), jsnlogConfiguration);
并显示日志消息。
如果有帮助,请告诉我