LOGGING in ASP.NET Core | Getting Started With ASP.NET Core Series

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone welcome back to the youtube channel and my name is rahul dotnet core supports a logging api that works with a variety of built-in and third-party logging providers logging providers usually store logs except for a few like console which displays them in this video we will learn more about the built-in logging providers in asp.net core how they are configured and how you can use them in your application heading off to my console let's use the dotnet cli to create a new asp.net web api application this is going to create a new web api application into the current folder let's open this application in an ide i will choose rider in this example you can choose whichever ide that you normally use to work with dotnet applications the project is loaded here and it has a program.cs and a startup.cs file as expected it also has a controller which is the weather forecast controller to start with let's first create a log statement in this template to do that let's go to the weather forecast controller in the constructor we see that we have an eye logger of weather forecast controller already injected in however this is not getting used at the moment so let's make use of this so let's write underscore logger and specify the log statement and given a log level so in this case this is basically an information and it needs a message for this particular log let's say hello from weather controller let's put a breakpoint here and run this application to see how this works the application has started and it has automatically called the weather forecast endpoint we have the breakpoint and it's calling the logger.log method so let's step into it and go to the console to see that particular message coming up in the console we have successfully written a log message to the console provider let's see how this is working under the hoods and how it started logging into the console provider let's stop this application and go to program.cs in the create host builder method we call a host.createdefaultbuilder this is a framework provided method that we are using to initialize the builder let's see how this create default builder method is implemented in rider i can simply use f12 to go to the definition and it will automatically disassemble the source code for me if you are on a different ide you can also configure this there however rider provides this by default alternatively you can also go to the github and view the source there let's scroll down in the create default builder and go to the place where the logging is configured using the configure logging method this first checks if it is a windows environment and it adds a few filters in that case after that it sets up the configuration for the logging which is basically reading from a section called logging which we will come later in this video this is where it is setting up the default logging providers you can see it's setting up the console the debug the even source logger and if this is windows it also sets up the event log provider so by default asp.net core template is setting up four providers for this application this is the reason why we could see this message in the console when we ran the application before you can override the defaultly specified providers in your program.cs class so let's head back to program.cs and after the configure web host defaults you can add in an extension method which is the configure logging method so this takes in a logging builder so let's use that and then we can start operating on that builder you can call the clear providers which will clear off all the logging providers that's registered into this builder so let's call that for example and let's run this application again in this case we should not be seeing the log message in the console because there are no providers that set up for this application right now we have hit the logger however running that statement doesn't produce any logs in the console right now because we cleared off all the providers you can call in the builder dot add console which is going to add the console provider this should start logging in back like we saw before so running this we now have the hello from weather controller message back in the console let's look at what's happening in the weather forecast controller it takes in an eye logger of weather forecast controller which is injected in using the dependency injection service if you want to learn more about dependency injection and how that works in asp.net core check out the video link here or in the description below the weather forecast controller type is basically specifying the category for that logger once we have the logger instance we use the log method on it to write the message into the logs here we also specified a log level which is an enumeration in this case we use the log level dot information showing that this is just an information message the category set on the i logger is simply an arbitrary string by convention it's usually set to the class name that the logger is used in so in this case it's using the i logger of weather forecast controller but since this isn't convention there's nothing stopping us from using this as a different value let's say for example instead of i forecast controller we can inject in an eye logger of weather forecast make sure that we have the read-only property also reflect the same type and then use this for writing the messages so if we were to run this this is now going to use the weather forecast as the category which you can see here in here logging and it specifies logging.weatherforecast so this is the fully qualified name of the weather forecast class if we go into the definition you can see this belongs to the namespace logging and the class name is weatherforecast which is why you see here as logging.weatherforecast if we go back to the weather forecast controller and change this back to weather forecast controller we can see it should now start showing the weather forecast controller as the category let's rerun the application and we see this time the category is logging controllers weather forecast controller the log level indicates the severity of the log this is an enumeration which has different values let's go to the definition of that and we can see it has different values trace debug information warning error critical and none this is in the order of severity of the log level so let's go back instead of using the log method and specifying the log level explicitly we can also use the extension methods that's available as part of the logger class so we can specify logger and specify log information which is exactly as specifying the log level dot information and given the message hello again from the controller so if we run this this is going to look exactly same as the line before because we've used the log information extension method to specify the log level information so if you see we have the same logging info controller and it's specifying info on both the cases so here we have the category set to the exact same value if we go into the definition of log information using f12 in rider we can see that it uses the logger.log method and calls in the log level.information for us and passes on the message and the arguments if there are any similar to the log information we also have extension methods for the other log levels that we saw so if we use the log method we can see we have log information log error log trace log warning log critical and log debug methods this sets the appropriate log levels when creating the log messages so if we were to use the log warning for example and say this is a warning that's going to set the log levels to warning so let's run this and see how that's represented in the console you can see that this has created a new warning message which is saying this is a warning note the color coding here to indicate that it is a warning you can also log exceptions using the log error method let's create an exception here and try logging that so in this case let's add a try catch block instead of the default console.writeline we can remove that and create a logger statement so let's say underscore logger and specify log error this takes in an exception as its object and also a message so we can say error in creating object let's throw a new exception and save this as a test exception let's run this and see how that appears the exception is now getting logged and it shows a failure message in the console it also logs out the error message that we specified and also the details of the actual exception that occurred each log can have associated and even id and even id allows us to group different logging messages so let's say all our get methods have a specific event id to specify an even id let's use the logger and use the log information method and specify an event id to start with this is simply a number that you can specify so let's give 1001 and then given a message so getting weather forecast details let's run this and see how the event id appears in the console logger as you can see it's logged out this message here getting weather forecast details and you can see the event id specified in the brackets in the console provider depending on the provider it might choose to log this or also ignore this some providers also save this as a separate field which allows you to query and filter on these log events rather than hard coding the log ids in here you can also use this from a shared class or from a constants class however you want to manage them the log message specified here is a message template and it can take in parameters to do that use a curly bracket and specify the parameter name let's say count and then pass in the parameters as values after the message we can pass in a 5 in here so this will be replaced by 5 when the log is written let's run this and make sure it's working as expected we can now see the message here getting weather forecast details and it also shows the number 5 which was replaced in here this gets replaced in the order that the parameters occur so you need to make sure the order in which the arguments are passed in is correct let's say in here if we have a p1 and p2 getting passed into the message template the order is important so if we specify p2 first even though this is p1 that's coming up it's going to pass in the p1 value for there if we run this we can see the value is coming as parameter 1 and parameter 2. even though the template specified the parameter 2 to be first to fix this we'll either need to fix the template or the way in which we are passing the parameters so i'll simply make this as p1 and make this as p2 to fix this in this particular instance these arguments are passed on to the different logging providers and not just the string template which enables them to do whatever they require let's see this for an example by adding a different logging provider for this example let's configure an external provider which is called seek which helps us to visualize logs in a much better format if you have not used seek before i highly recommend checking it out you can run this on your local machine by downloading it from here once installed you can use the browse seek shortcut in your start menu or explicitly navigate to localhost colon 5341 which is the default port where seek gets installed so this loads up a visualization to see all the logs let's see how we can configure asp.net core to log to seek as well as you would expect we need to install a nuget package so let's go to the project right click the project and say manage nuget packages we need to install the seek extension dot logging library so this is seek.extensions.logging so let's install that to this project that is successfully installed so let's go back to program.cs where we first cleared all the providers and added in the console so here we can now specify builder.add seek this is now provided by the nuget library that we just installed once we set this up we should be able to visualize the logs created by this application in our local instance of seek which it is defaultly configured to you can overwrite the server details in here using parameters however i will leave it to default and use the localhost 5341 as itself let's run this and make sure everything is working as expected the application is now running if we go back to the console we can see all the log messages that it has generated it is also created the errors and the warnings let's head off to seek and refresh this to see it reflecting in here as well so we can see some messages here which is the hello from weather controller that we wrote the hello again the warning message and the error objects and also the parameter values if you were to click that we can see more details that's associated with that particular log message we specified in the getting weather forecast details we specified an id and a count so let's go back and see how that is getting represented we have the event id specified here which is 1001 and also the count that appears as an attribute that we can filter on the message is as expected as in the console message similarly for the parameters we have the values for p1 and p2 which was passed into the template this is basically an example of structured logging if you want to know more check out the link in the description below this now allows us to filter these logs quite easily let's say we want to see only the ones which has a count of 5 so i can come here and click and say find with any value or specify find which is going to say which is only having the property count is 5 and it just displays 1 of the log message now that we know how to configure providers and also write log messages let's see how we can control the amount of logs that gets written on different environments using the appropriate log level is the most important thing when writing a log level message make sure you use the correct log level for that particular message in the end the number of messages that get stored is also equating to money because you need to pay for storage we can use the login configuration to limit the kind of logs that gets written to a particular storage based on the environments logging configuration is best specified outside of code as config files we had seen in a previous video how to specify configuration in asp.net core check out the link here or in the description below to get more details by default the asp.net core specifies the logging template in the appsettings.json file so let's go to appsettings.json and we can see the login configuration here the logging property in the config can have the log level and also the log provider properties inside it by default only the log level is specified any default message is configured here to be information each of these values under the log level specifies a category and an associated log level that needs to be logged for that category so in this case anything that is information or greater than information log level is going to get logged when we saw log level we had seen how the severity was ordered so when anything is greater than information which means information warning error critical gets logged for that particular provider so here this is the default so any default log message is going to log only above information so if we have a trace log it's not going to get logged in this particular example so let's go back to the weather forecast controller and add in a trace log to test this out so let's specify log trace which is going to add the log level as trace and say this is a trace message now since the config specifies only logs with the level of information or greater needs to be logged this is going to get ignored to get this to work let's update the configuration since this is running in the development environment we need to check the app settings.development.json file as well which also specifies a login configuration so let's modify it here because this is going to defaultly take precedence over the logging that's specified in appsettings.json so let's change the information here to b trace so this is going to start logging any messages that's trace or greater than that we can now see we have a trace message and that this is a trace message is logged in the console the logging configuration can also be overridden based on the provider so let's say in case where it is a seek provider we don't want the default to be traced but to be information so let's use seek to specify the provider and given the login configuration for that once we have the provider name we need to specify this exact same structure below that we can turn this back to information since in the previous run we didn't have this configuration zeek would have written that trace message as you can see here let's keep a node of the time here which ends with 202 and now we can start running this we should not log this anymore because we have overridden the config for seek so let's run this application as expected in the console we still see that trace message however if we are to go back to seek and refresh this we will not see a trace message so you can see that this is a trace message no longer appears here in seek this is because we use the configuration to suppress that particular level for that particular provider the values that appears here are basically categories so if we want to overwrite for the category that we have just written we could do that as well so let's specify the category logging.controllers.weatherforecastcontroller and use that to overwrite the levels for this so we can give in a log level that needs to be logged for this particular category so let's specify only errors should be logged for this category so we can specify error and run this application to check if everything is working as expected and now you can see that for the logging controller's weather forecast controller category it's only logging the error messages this is because we have specified in the config that only error log levels must be written let's change that back to information so that all messages gets logged you can use a logging scope to group a set of logical operations this allows us to add common attributes or properties into that particular scope to use a logging scope we can use the underscore logger and specify the begin scope method this takes in a dictionary of objects which can be any values that you want to attach with this particular scope so here i have specified a person id with this particular scope and also logging to messages which is hello and world which are information let's run this we can see in seek these two messages appearing so we have world and hello and note that the person id gets logged for both these log messages so you can group these different logs to be part of a single operation so if you have an http request context or a particular transaction that you are trying to track across multiple log messages you can use this to group a set of logical operations for the console provider to log this you need to explicitly enable it in the configuration if you want to write a log in the startup class you can inject in an ilogger or startup into your configure method to do that go to the startup class and in the configure method you can inject in like here and you can specify the logging messages like we saw before so we can specify log information and save from startup class note that writing logs before the completion of the dependency injection container setup is not supported which means you cannot inject a logger into the startup constructor nor into the configure services method which basically sets up the dependency injection by default asp.net core includes these logging providers which allows us to log to the console debug even source even log azure app services and also application insights you can also use third-party logging providers like sirilog alma or log4net for example integration is quite easy and it's very similar to just calling an extension method like we did for adding the seek make sure to check out this blog post which will be linked in the description below which provides some good recommendations and practices when using the logging library hope this helps you to understand more about logging in asp.net core if you like this video please make sure to hit the like button if you want to be notified in the future of similar such videos please make sure to subscribe thank you and see you soon
Info
Channel: Rahul Nath
Views: 10,185
Rating: undefined out of 5
Keywords: asp.net core logging tutorial, asp.net core mvc logging, asp.net core logging middleware, asp.net core logging providers, asp.net core logging example, .net core logging config, .net core logging, logging in .net core 3.1, logging in .net core, logging in .net
Id: dxBlBltEDRs
Channel Id: undefined
Length: 21min 23sec (1283 seconds)
Published: Wed Aug 19 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.