.net Core 2.2 API logging for front-end in Serilog

The setup is a Front-end and a Back-end. Logging for Back-end in Serilog is quite straight forward. Things got a bit hairy when it was required to supply an API for logging Front-end errors and distinguish between the two in the Log table. In this post will show how this was achieved.

The project is same like the one in this post, however this is simpler so creating a repository for this is not required.

Create a LogController, this will be used to log from the front-end. Setup the action how you wish to send your errors and level of detail.

        // POST: api/v1/Log
        [HttpPost]
        public void Post([FromBody] string value)
        {
            Log.Information(value);
        }

Now to distinguish between back-end generated logs, an Enricher is used.

    public class LocationEnricher : ILogEventEnricher
    {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            try
            {
                if(logEvent.Properties["RequestPath"].ToString().Contains(@"/api/v1/Log/"))
                    logEvent.AddOrUpdateProperty(propertyFactory.CreateProperty("Location", "FrontEnd"));
                else
                    logEvent.AddOrUpdateProperty(propertyFactory.CreateProperty("Location", "BackEnd"));
            }
            catch
            {
                // ignored
            }
        }
    }

What this does is check that this is coming from /api/v1/Log path and if so sets “Location” property to Frontend, else Backend.

 
              .UseSerilog((context, config) =>
              {
                  config.ReadFrom.Configuration(context.Configuration);
                  config.Enrich.WithLocation();
              })

Add the column to the appconfig.json

  "columnOptionsSection": {
            "customColumns": [
              {
                "ColumnName": "Location",
                "DataType": "nvarchar",
                "DataLength": 20,
                "AllowNull": true
              }
     ]
  }

This is pretty much it, easy eh?

One might get more sophistication in the logging from Front-end and distinguish the type of logic.

        // POST: api/v1/Log
        // Do some magic here ;)
        [HttpPost]
        public void Post([FromBody] string value)
        {
            Log.Information(value);
            Log.Debug(value);
            Log.Error(value);
            Log.Warning(value);
            Log.Fatal(value);
        }

But that is outside of the scope of this post.

Please like & share:

Leave a Reply