简体   繁体   English

Serilog / JSNLog .NET Core记录空JSON

[英]Serilog / JSNLog .NET Core logging empty JSON

I have a .NET Core project using Serilog and JSNLog for client side logging. 我有一个使用Serilog和JSNLog进行客户端日志记录的.NET Core项目。 If I pass a JSON object from the client to the server and log it using Serilog, the logged JSON object is empty. 如果我将JSON对象从客户端传递到服务器,并使用Serilog进行记录,则记录的JSON对象为空。

The very weird thing is that, if I have the debugger attached, the JSON is logged fine. 十分奇怪的是,如果我附加了调试器,则可以很好地记录JSON。

For example: 例如:

While debugging I get: 在调试时,我得到:

[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

When Crtl+F5 I get: 当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

I'm not sure if the problem is with Serilog or JSNLog, but any help would be appreciated. 我不确定问题出在Serilog还是JSNLog,但是可以提供任何帮助。

I've made a very simple sample app to replicate this. 我制作了一个非常简单的示例应用程序来复制它。 Using the default .NET Core Webapp 使用默认的.NET Core Webapp

Dependencies are as shown: 依赖关系如下所示: 依赖

in Startup.cs: 在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?}");
            });
}

And in my front end: 在我的前端:

<script src="~/lib/jsnlog.js/jsnlog.min.js"></script>
    <script>
            JL().fatal({ testMessage: "this is an error" });
            JL().fatal("this works");
        </script>

I had a similar issue. 我有一个类似的问题。 I took a look at JSNLog and what seemed to be the issue was the logging of the JSON .NET object that was being created when desearializing an object from the log message. 我看了一下JSNLog,似乎出现的问题是从日志消息中反序列化对象时正在创建的JSON .NET对象的日志记录。

I did the following workaround: 我做了以下解决方法:

  1. I installed the Nuget package Destructurama.JsonNet ( Install-Package Destructurama.JsonNet ) 我安装了Nuget软件包Destructurama.JsonNetInstall-Package Destructurama.JsonNet
  2. Then I changed the Logger configuration to include the destructuring: 然后,我更改了Logger配置以包括解构:

     Log.Logger = new LoggerConfiguration() .Destructure.JsonNetTypes() .WriteTo.Console() .CreateLogger(); 
  3. I then created a CustomLoggingAdapter class like this: 然后,我创建了一个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; } } } 

    and changed the log to have the following format {@logMessage} 并将日志更改为以下格式{@logMessage}

Note: LogMessageHelpers.DeserializeIfPossible can be found in the JSONLog GitHub repo 注意:LogMessageHelpers.DeserializeIfPossible可以在JSONLog GitHub存储库中找到

  1. Then I changed the JSNLog configuration to take in my CustomLoggingAdapter like this: 然后,我将JSNLog配置更改为将CustomLoggingAdapter如下:

      app.UseJSNLog(new CustomLoggingAdapter(loggerFactory), jsnlogConfiguration); 

and the log messages appeared. 并且出现日志消息。

Let me know if that helps 让我知道是否有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM