How I can write a json or text file from the build -in logger provided in Asp.Net MVC core 6 ?

mehmood tekfirst 766 Reputation points
2022-07-19T08:21:44.58+00:00

How I can write a json or text file from the build -in logger provided in Asp.Net MVC core 6 ?

I Need to create a log file on daily bases either in a json file or a txt file.

I am getting this exception on server in event viewer.

What does that mean ?

System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it. (localhost:7177)  
 ---> System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it.  
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)  
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)  
   at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)  
   at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)  
   --- End of inner exception stack trace ---  
   at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)  
   at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)  
   at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)  
   at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)  
   at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)  
   at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)  
   at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)  
   at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)  
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)  
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)  
   at AspNetCoreGeneratedDocument.Views_Home_FindBranch.ExecuteAsync() in D:\Git Source Code\Practical\Release1\Practical_1\CarRentalWidget\Views\Home\FindBranch.cshtml:line 18  
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)  
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)  
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)  
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)  
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)  
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, String contentType, Nullable`1 statusCode)  
   at Microsoft.AspNetCore.Mvc.ViewFeatures.PartialViewResultExecutor.ExecuteAsync(ActionContext context, PartialViewResult result)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultFilters>g__Awaited|28_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)  
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)  
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)  
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)  
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)  
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)  
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,080 questions
{count} votes

Accepted answer
  1. Ruikai Feng - MSFT 2,521 Reputation points Microsoft Vendor
    2022-07-20T18:36:38.883+00:00

    Hi,@mehmood tekfirst
    Writting a log file was not provided by default,you could try with a third-part tool or try to create a custom IloggerProvider,
    I tried as below:

    public class CustomFileLogger : ILogger  
        {  
      
            private readonly string _name;  
            private readonly CustomFileLoggerConfiguration _config;  
            private LogLevel _logLevel;  
      
            public CustomFileLogger(string name, CustomFileLoggerConfiguration config)  
            {  
                _name = name;  
                _config = config;  
            }  
      
            public IDisposable BeginScope<TState>(TState state)  
            {  
                return null;  
            }  
      
            public bool IsEnabled(LogLevel logLevel)  
            {  
                return logLevel == _config.LogLevel;             
            }  
      
            public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)  
            {  
                if (!IsEnabled(logLevel))  
                {  
                    return;  
                }  
                _logLevel = logLevel;  
                FileLog($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:fff")} - {logLevel.ToString()} - {_name} - {formatter(state, exception)}");  
            }  
      
            private async void FileLog(string strLog)  
            {  
                var sb = new StringBuilder(strLog);              
                sb.AppendLine();  
                var targetstr = sb.ToString();  
                string fileName = DateTime.Now.ToString("yyyy-MM-dd") + "_" + _logLevel.ToString() + ".txt";  
                string filePath = _config.LogPath + "\\" + fileName;  
                File.AppendAllText(filePath, strLog);  
                await File.AppendAllTextAsync(filePath, targetstr);  
            }  
        }  
      
        public class CustomFileLoggerConfiguration  
        {  
              
      
            public LogLevel LogLevel { get; set; }   
            public string LogPath { get; set; }  
        }  
      
      
        public class CustomFileLoggerProvider : ILoggerProvider  
        {  
      
            private readonly CustomFileLoggerConfiguration _config;  
      
            public CustomFileLoggerProvider(CustomFileLoggerConfiguration config)  
            {  
                this._config = config;  
            }  
      
            public ILogger CreateLogger(string categoryName)  
            {  
                return new CustomFileLogger(categoryName, _config);  
            }  
      
            public void Dispose()  
            {  
      
            }  
        }  
    

    in program.cs:

     builder.Logging.AddProvider(new CustomFileLoggerProvider(new CustomFileLoggerConfiguration  
        {  
            LogLevel = LogLevel.Information,  
            LogPath = builder.Configuration["FileLogPath:LogPath"]  
        }));  
    

    in appsettings:

     {  
          ...  
          "FileLogPath": {  
            "LogPath": "C:\\Users\\ruikaif\\Desktop"      
          },  
         ...  
        }  
    

    in controller:

    public class HomeController : Controller  
        {  
            private readonly ILogger<HomeController> _logger;  
      
            public HomeController(ILogger<HomeController> logger)  
            {  
                _logger = logger;  
            }  
      
            public IActionResult Index()  
            {  
                _logger.LogInformation("hellow");  
                _logger.LogInformation("test");  
                return View();  
            }  
        }  
    

    The Result:

    223660-2022-07-22-185033.png

    ----------

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards
    RuikaiFeng

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful