Showing posts with label Asp.net Core. Show all posts
Showing posts with label Asp.net Core. Show all posts

Sunday, 4 March 2018

Request Linking in asp.net core


In systems where events are processed in several microservices is useful to maintain a request identifier to be able to link logs from each microservice to do some investigation or to measure performance.
So far we have relied in a custom http header and owin middleware to read, add a new segment to this request identifier and then set it in the log4net context so it can be written when logging an event.
For a new asp.net core service I'm working, I have quickly put together new middleware to do the same operation using the documentation, but instead of using log4net I have found that it is easier to use NLog to capture the TraceIdentifier property in the HttpContext.

Middleware

public class TransactionLinkingMiddleware{
private readonly RequestDelegate _next;
public const string ParentTransactionHttpHeader = "Transaction-Link";
public TransactionLinkingMiddleware(RequestDelegate next)
{
 
_next = next;   
}
public Task Invoke(HttpContext context)
{
if (context.Request.Headers.TryGetValue(ParentTransactionHttpHeader, out var headerValues)
                                    && headerValues.Any())
{
context.TraceIdentifier = $"{headerValues.First()}/{context.TraceIdentifier}";
}
// Call the next delegate/middleware in the pipeline
return this._next(context);
}
}

public static class TransactionLinkingMiddlewareExtensions{   
public static IApplicationBuilder UseTransactionLinking(this IApplicationBuilder builder)
                  {        
return builder.UseMiddleware<TransactionLinkingMiddleware>();
}
 
}

Startup.cs

public Startup(IConfiguration configuration, IHostingEnvironment env)
{   
Configuration = configuration;    env.ConfigureNLog("NLog.config");
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory,    IApplicationLifetime applicationLifetime)
{
if (env.IsDevelopment())
{       
app.UseDeveloperExceptionPage();
}
app.UseTransactionLinking();
loggerFactory.AddNLog();
app.UseMvc();
}

NLog.config

<?xml version="1.0" encoding="utf-8" ?><nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"> 
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<target xsi:type="File" name="File"
fileName="${basedir}/logs/log.txt"
layout="TimeStamp=${longdate} Level=${uppercase:${level}} Transaction=${aspnet-TraceIdentifier} Message=${message}" />
</
targets> 
<rules>
<logger name="*" minlevel="Debug" writeTo="File" />
</rules>
</nlog> 

NLog.Web and NLog.Web.AspNetCore packages need to be installed https://github.com/NLog/NLog.Web

Thursday, 4 January 2018

Longer, slower and lazy path back to the start

Right before Christmas holidays I started some work on a new microservice and agreed with the team to use Asp.net Core on the .net Framework as it was a good opportunity to start introducing Asp.net Core in our stack without having to go to .net core straight away.
This morning I came back from my two weeks off just to find out that one of the guys had expended a considerable amount of time trying to setup a build in Teamcity for this solution only to give up and then "downgrade" it to Asp.net; and the worst part is that it wasn't because of a tight deadline and the code had not advanced much from the version I had left....
After taking a deep breath, and having a chat with the other members of the team that weren't on holiday we decided to use Asp.net Core again. As I predicted, getting the build to work in Teamcity was fairly straightforward as I had already installed and configured the agents a while ago when I was working on some Akka.net .net core projects. 
Unsurprisingly, most of the effort went into "rolling back" the downgrade and removing packages for injection of dependencies and logging that are not longer needed. So I'll keep my "fight" on for the team to learn and use new technologies where it makes sense instead of sticking to the "same old" out of pure laziness...