Serilog not recording logs to file when i publish app - serilog

I'm using this guide to quickly setup logging to a file in an asp.net core app with the least hassle.
https://github.com/serilog/serilog-extensions-logging-file
I seem to be getting logs but they are more like default logs of program startup and api requests. The logs that i'm writing with the below code are not appearing in the text file
_logger.LogInformation("important logs here");
Second problem is that when i publish my application, it runs fine but does not produce any log files.
Below is my program class
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).ConfigureWebHost(config =>
{
config.UseUrls("http://*:5050");
}).ConfigureLogging((hostingContext, builder) =>
{
builder.AddFile("Logs/myapp-{Date}.txt");
})
.UseWindowsService();
}

Related

How to configure Program.cs without startup.cs? .NET 6.0

The instructions at Electron.NET instruct to add the following snippets to my .NET 6 project for Electron to run.
Add to Program.cs:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseElectron(args);
webBuilder.UseStartup<Startup>();
});
Add to Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
// Open the Electron-Window here
Task.Run(async () => await Electron.WindowManager.CreateWindowAsync());
}
Since there is no longer a Startup.cs file, how do I convert this code to a usable state for a modern Program.cs file?
Obviously it's not as simple as putting all the code into a modern Program.cs file. I scoured google for an answer to this issue and didn't find anything. I also poured through the documentation in the github repository and Electron website. I don't have the experience to figure this out on my own and would love some help.
This works for me:
Program.cs
using ElectronNET.API;
using ElectronNET.API.Entities;
namespace tests;
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddElectron();
builder.WebHost.UseElectron(args);
if (HybridSupport.IsElectronActive)
{
var window = await Electron.WindowManager.CreateWindowAsync(
new BrowserWindowOptions
{
Width = 500,
Height = 250
});
window.OnClosed += () =>
{
Electron.App.Quit();
};
}
}
}
Pre-requisites
.NET 6
.NET 5 framework installed (at least runtime)
Node installed (for npm)
VS running as admin (I am running 2022 at time of writing)
Electron-API nuget package installed
Electron-CLI installed (dotnettool)
Result

create sub domains "sub.example.com" with .net core 5

i'm trying to create a sub domain for my website, something like "sub.example.com", i've been following a tutorial on youtube but it is not working, this is what i have done.
my startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton<SubdomainRouteTransformer>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapDynamicControllerRoute<SubdomainRouteTransformer>(
"{controller=Home}/{action=Index}/{id?}");
});
public class SubdomainRouteTransformer: DynamicRouteValueTransformer
{
public override async ValueTask<RouteValueDictionary> TransformAsync(
HttpContext httpContext,RouteValueDictionary values)
{
var host =httpContext.Request.Host.Value;
var subdomain = httpContext.Request.Host.Value.Split(".")[0];
if(!string.IsNullOrEmpty(subdomain)){
values["controller"]= subdomain;
}
return values;
}
}
program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseUrls("https://*.localhost:5001");
});
i have also registred new subdomains on my machine hosts file
127.0.0.1 admin.localhost
127.0.0.1 bugreport.localhost
i tried to create a break point on the TransformAsync method, it is getting hit by the compiler whenever i enter the normal URL address "https://localhost:5001".
when i enter sub domain address "https://admin.localhost:5001" TransformAsync method is never getting hit .
any help is appreciated
i've figured out this by myself, it seams like the solution above is working perfectly, the issue was with Safari, somehow the solution above did not work on it but it worked perfectly on chrome.
also another small detail is that you can skip the last step of setting the host file on your machine, the solution works without it.

How add startup class to worker service template in .net core 3

I want to add Startup class to worker service template in dotnet core 3 in order to use Configuration as dependency injection. I don't want to use my Program class to configure services. If there is another way to use Configuration, please give me an info about. Thank you.
this is my Standart program class code and I just added Hangfire
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHangfire(x =>
x.UsePostgreSqlStorage(Configuration.GetConnectionString("defaultConnection"))
);
services.AddHostedService<Worker>();
});
I just want to seperate my services to configure in Startup class
UseStartup<Startup>();
You can do this:
var configuration = hostContext.Configuration;
services.AddHangfire(x => x.UsePostgreSqlStorage(configuration.GetConnectionString("defaultConnection"))
else
services.AddHangfire(x => x.UsePostgreSqlStorage(hostContext.Configuration.GetConnectionString("defaultConnection"))

gRPC and MVC in same ASP.NET Core 3.0 Application

I am building out small, single purpose micro-services that require access via gRPC and Rest. We are implementing on ASP.NET Core 3.0. I realize this is pretty fresh stuff and have been looking for some reasonably complete reference implementations that demonstrate how to get this done.
I have a small .NET Service (Business Logic) call it IOrders. Now I want to wire up both gRPC and MVC (HTTP) against this back end service.
Any examples, github repos, blogs to follow or look around in would be greatly appreciated.
I had exactly same issue. I am runing.NET Core 3.0 and Grpc.AspNetCore Version 2.23.1. The biggest problem was to start it without SSL (not recommended for prod environments). Using certificate i found this github Secure_gRpc to be nice example.
Running without ssl for dev environments could be achieved in this way.
Program.cs file. Key aspects is to set HttpProtocols.Http1AndHttp2. I also removed certificate just to get it running. Uncomment next line to use SSL and certificate
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.ConfigureKestrel(options =>
{
options.Limits.MinRequestBodyDataRate = null;
options.ListenLocalhost(8008, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
listenOptions.UseHttps(adapterOptions =>
{
adapterOptions.ClientCertificateMode = ClientCertificateMode.NoCertificate;
adapterOptions.ServerCertificate = null;
});
//listenOptions.UseHttps("<path to .pfx file>", "<certificate password>");
});
});
});
}
Startup.cs is pretty straightforward. It is very important to remember if you modify Startup.cs file order of added services is very important. If it doesnt work try other order and/or find official documentation.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc((options => { options.EnableDetailedErrors = true; }));
services.AddMvc(options => options.EnableEndpointRouting = false);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseMvcWithDefaultRoute();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<GreeterService>();
});
}
}

How do I debug an ASPNET Core MVC Application Deployed in Azure

I've created a simple ASPNET Core 1.0 MVC app, which I am trying to deploy to Azure using Visual Studio. I am able to run this app locally on my machine using IIS Express, and navigate to my default route and display the page. However, in Azure I always get a 500 error every time, and at this point I am at a loss for how to get additional information.
I've enabled detailed request logging in my Azure app, but it doesn't really seem to tell me much.
ModuleName="AspNetCoreModule", Notification="EXECUTE_REQUEST_HANDLER", HttpStatus="500", HttpReason="Internal Server Error", HttpSubStatus="0", ErrorCode="The operation completed successfully.
(0x0)", ConfigExceptionInfo=""
I've stripped down my Startup configuration to the bare essentials
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggingFactory)
{
loggingFactory.AddConsole();
loggingFactory.AddDebug();
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
});
}
Something must be blowing up in the MVC pipeline but I have no idea how to add more visibility. What can I do to get more information?
And in case it matters, this is my Program.cs
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
Try setting ASPNETCORE_ENVIRONMENT to Development to display full exception message on the error page.
Remember to turn it off when finished, otherwise you will leak error information.

Resources