C
C#2mo ago
hutoanhill

✅ using Logging with ASP.NET

ASP.NET has a logging service. It looks way better than mine. I believe it gets set up here:
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();
Where can i find/modify this method? How can i trigger my own logs?
No description
66 Replies
Jimmacle
Jimmacle2mo ago
you can inject that logger with ILogger<TheTypeDoingTheLogging>
Jimmacle
Jimmacle2mo ago
Logging in .NET Core and ASP.NET Core
Learn how to use the logging framework provided by the Microsoft.Extensions.Logging NuGet package.
hutoanhill
hutoanhill2mo ago
ok, almost there. i figured out how to use the ILogger, but now i need to generate a new ILogger<MyType> logger and i cant figure out how to do that in a way that works...
Jimmacle
Jimmacle2mo ago
it should Just Work you don't need to generate that yourself, DI can figure out how to construct the service you're asking for
hutoanhill
hutoanhill2mo ago
yes, i passed app.Logger into my process, but it logs as though is ASP.NET. i think i explaned that badly... My App has two processes running: an ASP.NET api and a discord bot. right now when my discord bot needs to log something it just prints to the console. this works, but ASP.NETS logging looks way better so i want to implement this for my discord bot. So somehow i need to generate an istance of ILogger<Bot> that i can pass to my discord bot so it can log stuff and look nice. oh, ist an ILogger.
Jimmacle
Jimmacle2mo ago
i'm confused, what setup do you have for both processes to log to the same console?
hutoanhill
hutoanhill2mo ago
becasue i didnt know there was another option? theres one console...
Jimmacle
Jimmacle2mo ago
and do you actually need 2 processes compared to hosted services?
hutoanhill
hutoanhill2mo ago
i dont know how to create a hosted service.
Jimmacle
Jimmacle2mo ago
you could run the bot portion as a hosted service in your ASP.NET Core application
hutoanhill
hutoanhill2mo ago
that sounds more integrated at the least... i still want to create a seprate logger for the bot to more easily identify when the bot loggs somthing and when the API logs somthing.
Jimmacle
Jimmacle2mo ago
right, all that is involved in creating a "separate" logger is injecting ILogger<T> where T is any type you want (but typically the type you're injecting the logger into)
hutoanhill
hutoanhill2mo ago
Logger<Bot> discordLogger = new Logger<Bot>(new LoggerFactory());

Bot discordBot = new Bot(botConfig, discordLogger);
taskList.Add(discordBot.Run());
Logger<Bot> discordLogger = new Logger<Bot>(new LoggerFactory());

Bot discordBot = new Bot(botConfig, discordLogger);
taskList.Add(discordBot.Run());
This doesnt work when i try and log somthing it dosnt do anything.
Jimmacle
Jimmacle2mo ago
i don't know what that is, that's not what i'm recommending
public class MyClass
{
public MyClass(ILogger<MyClass> logger)
{
logger.LogInformation("Hi I'm Logging");
}
}
public class MyClass
{
public MyClass(ILogger<MyClass> logger)
{
logger.LogInformation("Hi I'm Logging");
}
}
then when you create that class through DI it will inject an appropriate instance for you alternatively get it yourself with serviceProvider.GetRequiredService<ILogger<MyClass>>() there's a whole bunch of logging infrastructure that is set up for you in DI, but with your code you're basically creating an empty unconfigured logger so it won't do anything
hutoanhill
hutoanhill2mo ago
in this block of code, i generate a Logger with the type of my Bot class. Then i pass that logger inot my discord bot and run it.
Jimmacle
Jimmacle2mo ago
but that's not how you're supposed to use the ASP.NET Core logging infrastructure which is why it's not working
hutoanhill
hutoanhill2mo ago
Ok and your saying i have to make my bot a hosted service before it can access that?
Jimmacle
Jimmacle2mo ago
no i'm saying that's better than 2 processes, but at this point i don't think you're actually using 2 processes so i'm confused 2 processes would mean you have 2 different exes that you're running but if you want to run a discord bot in-process with your ASP.NET Core application, a hosted service is the most proper way to do that
hutoanhill
hutoanhill2mo ago
no i am not doing that, sorry i don't have a lot of the nomenclature yet :( perhaps this will help:
List<Task> taskList = new List<Task>();

taskList.Add(app.RunAsync());



if (botConfig != null) {

Logger<Bot> discordLogger = new Logger<Bot>(new LoggerFactory());



Bot discordBot = new Bot(botConfig, discordLogger);
taskList.Add(discordBot.Run());
}
else {
Console.WriteLine("The bot config is null, skipped starting up the bot.");
}

await Task.WhenAll(taskList);
List<Task> taskList = new List<Task>();

taskList.Add(app.RunAsync());



if (botConfig != null) {

Logger<Bot> discordLogger = new Logger<Bot>(new LoggerFactory());



Bot discordBot = new Bot(botConfig, discordLogger);
taskList.Add(discordBot.Run());
}
else {
Console.WriteLine("The bot config is null, skipped starting up the bot.");
}

await Task.WhenAll(taskList);
This is the end of my main method. after it builds the my API it adds the task running the API and the task running the discord bot to a list and runs them symaltaniously
Jimmacle
Jimmacle2mo ago
i mean, that's a way to do it but definitely not standard
hutoanhill
hutoanhill2mo ago
only way i know how to do it, so i am doing it. Whats the normal way?
hutoanhill
hutoanhill2mo ago
so createing a hosted service... i thought i wasent running a service? you said you expected that to be its own exe...
Jimmacle
Jimmacle2mo ago
when you say "2 processes" that means "2 exes" i never brought up processes, you shouldn't have 2 if you want to run a long-running task inside an ASP.NET Core app (like a discord bot) then hosted service is the correct solution
hutoanhill
hutoanhill2mo ago
ah i see. so i need to implement my bot as a hosted service of the ASP.NET api. Then i can use the ASP.NET logging infostructure.
Jimmacle
Jimmacle2mo ago
you register the hosted service in your app's DI and it will start and stop it for you when needed
hutoanhill
hutoanhill2mo ago
ok, i will be back after i figure that out. the registering it as a hosted service
Jimmacle
Jimmacle2mo ago
the general look of a hosted service and registering it is this section in particular https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-8.0&tabs=visual-studio#timed-background-tasks if you inherit from a BackgroundService instead of implementing IHostedService it will take care of a lot of the boilerplate for you
hutoanhill
hutoanhill2mo ago
ok. that was super useful i think the last hurtle is my bot needs to access values within appsettings.json. How can a hosted service access the builders configuration? prevously i did this by calling builder.Configuration.GetSection("BotSettings").Get<DiscordSettings>(); then passing this value to the instance of bot, but i am not calling bot anymore
hutoanhill
hutoanhill2mo ago
stack exchange to the rescue: https://stackoverflow.com/a/58448732
Stack Overflow
Pass Parameters to AddHostedService
I am writing a .Net Core windows service and here is a snippet of code: internal static class Program { public static async Task Main(string[] args) { var isService ...
hutoanhill
hutoanhill2mo ago
ok. My Bot is a hosted service, and i can pass my bots config to it. now back to the Logger, i need to build a logger and pass that to the bot so it can log stuff. ideally a ILogger<Bot> instead of an ILogger<WebApplication> though that might block it?
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
not allowed to share this one :/
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
yep, everything's in appsettings.json now (which is not on the git)
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
separate project for an internship.
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
NDA.
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
ah no
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
stupid me sry
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
give me a few
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
Anchy
Anchy2mo ago
these hands are under NDA
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
GitHub
GitHub - hutonahill/huts-logging-tests
Contribute to hutonahill/huts-logging-tests development by creating an account on GitHub.
hutoanhill
hutoanhill2mo ago
wont actualy work if you compile it but it should get the message across.
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
... yep one sec thats super weird done
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
no i think that showed up when i was figureing out .NET identity...
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
yes, got a bunch of values the discord bot needs. figured no point in implimenting that here. not where the logger is or anything, but thats how the discord bot gets my token along with a bunch of other settings. dont know what you mean here... figgured
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
cool and that will grab the settings out of the appsettings.json file? under the BotSettings key?
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
yea, Secrets > appsettingsDevelopment > appsettings or somthing like that
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
hutoanhill
hutoanhill2mo ago
Thanks a ton!
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX2mo ago
If you have no further questions, please use /close to mark the forum thread as answered
hutoanhill
hutoanhill2mo ago
will do
Want results from more Discord servers?
Add your server