.Net Core : Logging system
Step 1
Create custom logger classusing System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace CoreDemo.Middleware
{
public class MyLoggerMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public MyLoggerMiddleware(RequestDelegate next, ILoggerFactory logFactory)
{
_next = next;
_logger = logFactory.CreateLogger("MyLogger");
}
public async Task Invoke(HttpContext httpContext)
{
_logger.LogInformation("test log");
//await _next(httpContext);
var bodyStream = httpContext.Response.Body;
var responseBodyStream = new MemoryStream();
httpContext.Response.Body = responseBodyStream;
await _next(httpContext);
responseBodyStream.Seek(0, SeekOrigin.Begin);
var responseBody = new StreamReader(responseBodyStream).ReadToEnd();
var responseCode = httpContext.Response.StatusCode;
var requestPath = httpContext.Request.Path;
var requestMethod = httpContext.Request.Method;
_logger.LogInformation($"@timeStamp = {DateTime.Now}, site = {"CoreDemo"}, Level = info, ThreadId = {Thread.CurrentThread.ManagedThreadId}, Message = logger Middleware response {responseBody}, request path = {requestPath}, request method = { requestMethod}");
responseBodyStream.Seek(0, SeekOrigin.Begin);
await responseBodyStream.CopyToAsync(bodyStream);
}
}
public static class MyLoggerMiddlewareExtension
{
public static IApplicationBuilder UseMyLoggerMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyLoggerMiddleware>();
}
}
}
Step 2
startup.cs public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMyLoggerMiddleware();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
Hope this will help you and save your time.
Enjoy !!!
:)
No comments:
Post a Comment