How can I change the log format of HTTP logging middleware in .NET 8

I have a requirement for creating Request/Response Logging. I am using default Logger implementation of Microsoft.

//Add Http Logging
builder.Services.AddHttpLogging(options =>
{
    options.CombineLogs = true;

    options.LoggingFields = HttpLoggingFields.RequestQuery | HttpLoggingFields.RequestPath |
        HttpLoggingFields.RequestBody | HttpLoggingFields.ResponseStatusCode | HttpLoggingFields.Duration;
});


//Using Middleware
app.UseHttpLogging();

In my appSettings.json file:

"Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information"
    }
  }

My issue is the default Log format of HTTP logging Middleware. This is what printed on my console:

info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[9]
      Request and Response:
      PathBase:
      Path: /api/film/rating
      QueryString:
      StatusCode: 200
      RequestBody: {
  "title": "G K Mon",
  "rating": "G"
}
      RequestBodyStatus: [Completed]
      Duration: 1595.698

Can I customize this default log format of HTTP Logging Middleware? Additional question is that how should I store logs in file without using Third party library.

/a/68363461/22971430

HttpLogging has pre-defined format/order and doesn’t have a built-in way to change. You could try implement a custom loggerProvider to modify the logmessage before log and then write to a file.

Reformat the logMessage before output.

    public class CustomHttpLogger : ILogger
    {
        private readonly string _filePath;

        public CustomHttpLogger(string filePath)
        {
            _filePath = filePath;
        }
        public IDisposable BeginScope<TState>(TState state) => null;

        public bool IsEnabled(LogLevel logLevel) => true;

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            var logMessage = formatter(state, exception);
            if (eventId.Name == "RequestResponseLog")
            {
                // Example: Reorder fields manually (string manipulation, regex, etc.)
                string reorderedLogMessage = ReorderLogFields(logMessage);

                // Output the reordered log message ,  if you use console without clearproviders you will find the default provider also logging.
                //Console.WriteLine(reorderedLogMessage);
                File.AppendAllText(_filePath, reorderedLogMessage);
            }
            //else
            //{
            //    Console.WriteLine(logMessage);
            //}
        }

        private string ReorderLogFields(string logMessage)
        {
            var messages=logMessage.Split("rn");
            string newMessage = "";

            newMessage += messages.FirstOrDefault(x => x.StartsWith("QueryString")) + "rn";
            newMessage += messages.FirstOrDefault(x => x.StartsWith("PathBase"))+ "rn";
            newMessage += messages.FirstOrDefault(x => x.StartsWith("RequestBody")) + "rn";
            newMessage += messages.FirstOrDefault(x => x.StartsWith("StatusCode")) + "rn";
            newMessage += messages.FirstOrDefault(x => x.StartsWith("Duration")) + "rn";

            return newMessage; 
        }
    }

Warp this logger to a logger provider

    public class CustomHttpLoggerProvider : ILoggerProvider
    {
        private readonly string _filePath;

        public CustomHttpLoggerProvider(string filePath)
        {
            _filePath = filePath;
        }
        public ILogger CreateLogger(string categoryName)
        {
            return new CustomHttpLogger(_filePath);
        }

        public void Dispose() { }
    }

Then added to logging providers

//This will clear the default providers, then only your custom provider will work.
//builder.Logging.ClearProviders();
builder.Logging.AddProvider(new CustomHttpLoggerProvider("E:\log1.txt"));
builder.Services.AddHttpLogging(options =>
{
    
    options.CombineLogs = true;

    options.LoggingFields = HttpLoggingFields.RequestQuery | HttpLoggingFields.RequestPath |
        HttpLoggingFields.RequestBody | HttpLoggingFields.ResponseStatusCode | HttpLoggingFields.Duration;
});

Test result

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật