<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>custom logging middleware .net core - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/tag/custom-logging-middleware-net-core/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Wed, 11 Jan 2023 15:07:22 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://thecodebuzz.com/wp-content/uploads/2022/11/cropped-android-chrome-512x512-1-1-51x51.jpg</url>
	<title>custom logging middleware .net core - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to log Headers in .NET Core API</title>
		<link>https://thecodebuzz.com/how-to-log-headers-net-core-api-request-forward-headers-logging/</link>
					<comments>https://thecodebuzz.com/how-to-log-headers-net-core-api-request-forward-headers-logging/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Fri, 01 Oct 2021 18:09:00 +0000</pubDate>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[.net core httpclient log request and response]]></category>
		<category><![CDATA[asp.net core logging to database]]></category>
		<category><![CDATA[asp.net core web api log all requests]]></category>
		<category><![CDATA[asp.net core web api logging to file]]></category>
		<category><![CDATA[custom logging middleware .net core]]></category>
		<category><![CDATA[how to get header value in web api c# .net core]]></category>
		<category><![CDATA[how to log request and response in asp.net core web api]]></category>
		<category><![CDATA[httpclient logging net core]]></category>
		<category><![CDATA[log headers in net Core]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=18813</guid>

					<description><![CDATA[<p>How to log or pretty print Headers value requests or responses in .NET Core API Today in this article, we shall see how to log headers in .NET Core requests or responses. In your .NET Core API, you may find the need to read the custom header value programmatically for understanding various headers used in [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/how-to-log-headers-net-core-api-request-forward-headers-logging/">How to log Headers in .NET Core API</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading"><strong>How to log or pretty print Headers value requests or responses in .NET Core API</strong></h1>



<figure class="wp-block-image size-large is-resized"><img fetchpriority="high" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2021/10/Logging-custom-header-in-.NET-Core-1024x440.jpg" alt="How to log Headers in .NET Core API, print headers ASP.NET Core" class="wp-image-18828" width="641" height="274" srcset="https://thecodebuzz.com/wp-content/uploads/2021/10/Logging-custom-header-in-.NET-Core-1024x440.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2021/10/Logging-custom-header-in-.NET-Core-300x129.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/10/Logging-custom-header-in-.NET-Core-768x330.jpg 768w" sizes="(max-width: 641px) 100vw, 641px" /></figure>



<p>Today in this article, we shall see how to log headers in .NET Core requests or responses.</p>



<p></p>



<p>In your .NET Core API, you may find the need to read the custom header value programmatically for understanding various headers used in the API communication. You may pretty print headers to understand the details of all headers flowing incoming or outgoing with request or response.</p>



<p></p>



<p>You may want to enable logging when headers aren&#8217;t transmitted as expected. </p>



<p></p>



<p>You can enumerate the request headers received by the server if the logs don&#8217;t provide enough information to troubleshoot the problem. </p>



<p></p>



<p>For more details on how to enable basic custom middleware in .NET Core, please visit the below article,</p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/add-custom-middleware-in-asp-net-core/" target="_blank" rel="noopener" title="Add Custom Middleware in ASP.NET Core"><strong>Add Custom Middleware in ASP.NET Core</strong></a></li>
</ul>



<p></p>



<p>Today in this article,  we will see how to read HttpContext request headers using 2 below-discussed approaches,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-using-inline-middleware-for-logging-custom-headers">Using Inline Middleware for logging custom headers</a></li><li><a href="#aioseo-using-custom-middleware-for-logging-headers">Using Custom middleware for logging Headers</a></li></ul></div>



<p></p>



<h2 class="wp-block-heading" id="aioseo-using-inline-middleware-for-logging-custom-headers">Using Inline Middleware for logging custom headers</h2>



<p></p>



<p>This is a very simple approach of using inline custom middleware for logging headers details.</p>



<p></p>



<p>Please Inject&nbsp;<code><strong><em>ILogger&lt;Startup&gt;</em></strong></code>&nbsp;into the class as described below in detail.</p>



<p></p>



<p>Here default ILogger interface can be used easily in configure method by updating Configure method as below,</p>



<p></p>



<p><strong>Example</strong></p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [2]; title: ; notranslate">
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
                      ILogger&lt;Startup&gt; logger)
{
    if (env.IsDevelopment())
    {
        logger.LogInformation(&quot;Log here&quot;);
        app.UseDeveloperExceptionPage();
    }
    else
    {
        logger.LogInformation(&quot;Log here &quot;);
        app.UseExceptionHandler(&quot;/Error&quot;);
        app.UseHsts();
    }
,
,
,
,
}

</pre></div>


<p></p>



<p>Let&#8217;s now add<strong><em> inline middleware</em></strong> as below,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [5,6,7,8]; title: ; notranslate">
app.Use(async (context, next) =&gt;
{

    // Log/Print all Headers
    foreach (var header in context.Request.Headers)
    {
        logger.LogInformation(&quot;Header: {Key}: {Value}&quot;, header.Key, header.Value);
    }

    logger.LogInformation(&quot;Request Method: {Method}&quot;, context.Request.Method);
    logger.LogInformation(&quot;Request Scheme: {Scheme}&quot;, context.Request.Scheme);
    logger.LogInformation(&quot;Request Path: {Path}&quot;, context.Request.Path);

    await next();
});

</pre></div>


<p></p>



<p>If you are using <strong><em>UseForwardedHeaders&nbsp;</em></strong>in&nbsp;<code>Startup.Configure</code> then make sure to use this middleware right after &nbsp;<strong><em>ForwardHeader </em></strong>middleware.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-using-custom-middleware-for-logging-headers">Using Custom middleware for logging Headers</h2>



<p></p>



<p>Above discussed approach can be used as Custom middleware,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
public async Task InvokeAsync(HttpContext context)
        {
            var _logger = _loggerFactory.CreateLogger&lt;CustomMiddleware&gt;();
 
            try
            {
                // Log/Print all Headers
               foreach (var header in context.Request.Headers)
               {
                 logger.LogInformation(&quot;Header: {Key}: {Value}&quot;, header.Key, header.Value);
               }
 
                await _next(context);
 
            }
            catch (Exception ex)
            {
                _logger.LogError($&quot;Something went wrong: {ex.Message}&quot;);
            }
        }
</pre></div>


<p></p>



<p>_logger instance can be injected as below,</p>



<p></p>



<figure class="wp-block-image size-large"><img decoding="async" width="922" height="243" src="https://www.thecodebuzz.com/wp-content/uploads/2021/10/Logging-custom-header-in-C-.NET-Core-ASP.NET-Core-MVC.jpg" alt="log or pretty print Headers" class="wp-image-18832" srcset="https://thecodebuzz.com/wp-content/uploads/2021/10/Logging-custom-header-in-C-.NET-Core-ASP.NET-Core-MVC.jpg 922w, https://thecodebuzz.com/wp-content/uploads/2021/10/Logging-custom-header-in-C-.NET-Core-ASP.NET-Core-MVC-300x79.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/10/Logging-custom-header-in-C-.NET-Core-ASP.NET-Core-MVC-768x202.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2021/10/Logging-custom-header-in-C-.NET-Core-ASP.NET-Core-MVC-785x207.jpg 785w" sizes="(max-width: 922px) 100vw, 922px" /></figure>



<p></p>



<p>Please see the below article on how to inject the <strong><em>ILogger </em></strong>interface into the custom middleware.</p>



<p></p>



<p><strong>References</strong>:</p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/add-custom-middleware-in-asp-net-core/" target="_blank" rel="noreferrer noopener"><strong>Add Custom Middleware in ASP.NET Core</strong></a></li>
</ul>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/using-httpclient-best-practices-and-anti-patterns/" target="_blank" rel="noreferrer noopener" title="Using HTTPClient Best Practices and Anti-Patterns"><strong><em>Using HTTPClient Best Practices and Anti-Patterns</em></strong></a></li>
</ul>



<p></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/how-to-log-headers-net-core-api-request-forward-headers-logging/">How to log Headers in .NET Core API</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/how-to-log-headers-net-core-api-request-forward-headers-logging/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
