Logging with NLog in ASP.NET

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi in this video are going to demonstrate end log or login for your application using c-sharp so we're going to take this application that we've built in the past and add some events to it that we can put in our server log so stick around and we'll see how to do that [Music] you so if you would like to use the exact same application that we're going to demonstrate here you can go back and do a tutorial that we've done in a previous lesson or if you have another favorite application that you just want to add logging to then you can continue on and adapt your changes as necessary so as you can see in our application we have a few views we have for login success and for failure we also have in our models section we also have a user model and so that'll give you an idea of what's going on here in our database we do have dbo users and if we want to see what's inside of there we can look at the data and you can see I have two users in the tables so if we want to add login to an application we need to use NuGet so I'm going to right-click on the activities title and choose manage NuGet packages so once you choose and managing packages you'll see things that are installed and things that are not installed so I want to browse to the things that are not installed yet and I'm going to search for in log which is the package here so we can see in log is a logging platform for dotnet so I'm going to choose this one I'll choose the version 4.7 and click OK also I want to choose n log config as another package all right so these are supposedly installed let's go check the install tab to see if they're there and sure enough I have installed three things with n log in the title so the next part that we're going to do is configure what we just set up as our logging so I'm going to the file called n log dot config and you can see that there's some XML commands here and the file that we're looking for or the part that we're looking for is down here where it says write events to a file so it gives us a template to follow I'm going to simply uncomment this section and use the example that they've given here so let's take the target area that they've recommended I'm going to copy it and come up to the area that calls targets and paste it so if you don't have this example in your in your setup here can copy it from mine so let's take a look at what it does so it says here that the type of file or the type of record that we're saving is a file so the next item that I'm going to change is name so name is the actual name of the target so I'm going to call mine my app longer target the next section over suggest a file name so you can see that base directory is the item that they choose first so that's the base directory of your application and then a subfolder in your app called logs and then they're going to use the name of the date so if it's March 20th it'll be you know all those three 20 20 20 or whatever the year is we all combined into one file name and then that log is a standard name for a file now then the layout is the actual line by line item that you're going to put in the log and the important one here is that the end is the message so whatever item that we're logging will be this is the content here and then of course the other stuff is the dates to tell us when it was logged now let's go down to the section called rules that says here add your logging rules here well they've given us a suggestion so I'm going to copy and paste the suggestion as well so the logger name let's change that from a star so I'll just put in my app log of rules as the name the min level so we can change this to different levels the one the one that we're going to pick is debug for right now and so this is the most verbose if you remember from the previous video that will get all of the details of the application then when the last section is right - we need to specify the name of a target and of course we name the target just a few minutes ago as my app logger target and so that'll be the configuration for our log so let's take a second here and look at what a real log will look like when we're done so I'm going to browse into another project and this one it was called activity 13 and it's not this exact same one but it does have a log in it so if I go into the logs folder where we've specified you can see that I have several log files that were created so this one here was done on march 18th and you can see that the format that we defined is here we've got the date we've got some kind of a login level so that doesn't say debug but it says info and then it has the message that I programmed in and it tells us the location so this is what your logs are going to look like by the time we're done so the next part of our logging application is to now place some items in our code to trigger an item in the log let's go to our controller so I'm going to switch to the controllers folder and go to the log in controller so if you're working on a different application you'll probably have a similar controller but we need to go here so the first thing I need to do in this controller is to set up a reference to the logger tools that we just installed when using NuGet so I'm going to instantiate a copy of logger the logger class and I'm going to have to use the parameters that we just created in the XML file my application logger rules is the parameter that I'm looking for and so this will initiate a new logger you can see that I also have to import these classes or use the using statement at the top of the page so for the first example I'm going to use a real simple method we're just going to log an info level message and so I'll put something like I'm entering the login controller using the login method let's also put in some alerts for the success and the failure for our login so I'll slip in here a line in the success section I'll say exiting the controller and log in was a success and we're using the info extension again so that's the level of logging that we're doing also at the same level here will do info as to say that the login failed and we'll put in a message for failure as well now there may have been some other code that I had put into this tutorial in a previous step so I'm not sure if I use try or catch before anyway I'm gonna put it in now so I'm gonna use a try and do the entire block of code that we've worked on just a second ago and also put in a catch now also is at the catch area I'm going to put in a log event now for the logger here I'm not going to put it as an info level log event it's a ever log event and so the error could occur for any reason in the exception so I'll just put in the e type message for our exception also I may have also included some other code in the previous tutorial about the model state and so we're just going to make sure that the state is valid so that they haven't put in numbers where they should have put letters and vice-versa so I'll just slip in an extra line of code to make sure that the valid model state is true so just a summary here we have an info level logging event an info level and info level and an error level at the login event so we should be able to see these in our logs when we run the application so let's give it a shot let's go ahead and log in and see if we can get a login success and a login failure alright it looks like the app is up and running so I'm going to go to the log in controller and give this a shot now what we're our my passwords again let's go back and check out the dbo users table i have max and penny as my only two people in the system so i can use either of those let's try max and his password is password one where they're just a one yeah okay let's go ahead and try the create button which is really the login button so it says success let's back up and let's put in a jump password and choose the button and it says failure so that should work let's go check out the logs so I'm going to my computer here I'm browsing the folders and I'm looking in the source area the repos and let's see this thing is called activity 3 in log it going activity 3 there is a folder called logs here somewhere so I'm looking at my folder and I'm looking for the folder called logs obviously it didn't work so I intentionally of course intentionally created an error so that you could see how to fix it so where's the mysterious logs folder it's supposed to be here let's go back and look on our n log config and see if I can trace down the error likely you'll have to do the same things so first of all I check to make sure that I've got my name here my app log or Target and that matches down here with the rules they're spelled the exact same way how about the logger rule itself this says app my app logger rule and when I created my login controller I probably spelled that differently so here it is my app logger rules so I think I need to fix this I'm either gonna copy this one copy this and paste it over top of the original or vice versa either way so let's save that and let's run the app again alright it looks like I'm up and running so I'm going to choose the login option and let's try a few more attempts at this let's go with Max and is password 1 we've got a success so that should be something in our log and let's put in some junk here and try again and we have a log-in failed alright back to the folders and let's take a look at activity 3 so here we are and sure enough there is a folder called logs it looks successful this time and today's date is the 25th let's double click it and here we go we've got ourselves a couple of infos and we got entering and exiting this looks like we're making some success so this log folder then is just a text file but if we had a more professional logging system a little bit bigger enterprise you might call it a level of more centralization this would all be copied to another location it would be put into a database it would be searchable it would go into a report and then this this is the this is the what he called the the raw material of the log product hey all right now we're going to turn the page and we're gonna do some refactoring so if you look at the code that I have on the screen I've made several changes so you can notice here in the line that initiates our logger we are now calling something called get instance now how did I create that well we're gonna answer that question in just a moment but first of all what are we looking at so this is called a singleton a singleton is a good type of design if you are creating a object that will be used throughout your program and you'll have exactly one instance of that object so the name singleton so Singleton's show up in things like logging because we want to have one logger for the whole application you'll also see Singleton's used in sometimes database connections so like you know at the beginning of the program you make an initial connection to the database and then throughout the program you want to use that same connection so you're not opening and closing connections all the time and so this is the pattern that we're going to fix right now so we're gonna have to create an interface and another design pattern you might call the facade so let's get started with that okay so I just returned the code to the position that it was in just a few minutes before so we have our instance right now as my logger listed as this line here on line 15 so let's get started with making this singleton pattern the first thing I want to do is to go find the folder in services over here services and let's open up the services area and let's create a new folder and we're gonna call this thing utility so new folder and utility so utility is the things where you put you know things that are kind of generally used throughout the whole program now I'm also going to add a new item here so let's choose a class and I'm gonna call this thing I logger so when you put the word I in front of something that kind of indicates that you're creating a interface so I'm going to erase the word class and change it to interface okay so interface is like you know probably from other programming that an interface is a pattern it's a contract all we're going to do is list the methods of a class and then the next iteration of this the one that it are the one that implements this will actually have to write the code so all we're gonna do is write down four different class methods here so the methods that we're going to create for this interface are going to be for the four different kinds of levels of logging so we're gonna have debug and we're gonna have warning and error and info and so we're going to accept a message and an argument so the argument we won't probably see much of but we're going to at least use a possible argument that is passed into this method and by the default it's set to null okay so we're going to implement a debug debug end we're going to implement an info and implement a warning and an error so all four of these are going to be methods that will be in our new logger and so we're just making the contract here to say expect to see these four names now let's go ahead and create the class that goes with this so let's go to the utility folder again and we're going to add a class so I'll switch there and this one we're gonna call my logger now you could guess that we are going to implement what I just created a second ago so let's go with high logger as our implementation so first of all you're going to say you're missing your implementation so let's take care of that right away so I'm going to choose show potential fixes under the light bulb and I'm going to implement the interface so there you have it we've got those four methods that we promised to create in the eye logger class so I'm gonna just ignore those for a little bit but we'll shove them down the page because they're for later so now I'm going to illustrate the pattern called a singleton singleton as the object that can only be instantiated one time and so we'll create some special code that will allow only one of them to exist so the first item that we're going to create as a property of my logger is called the instance so the instance is an instance of this name of this class my logger and so we'll just make it private and static so static is a key idea here you can only you can only make one of them okay so I'm trying to make a instance of the generic class called logger but as you can see my visual studio is not allowing me to do that automatically so let's go back and retype it so since I don't have the instance or don't have a class mention of logger it says hey what are you gonna do well fortunately we can use n log so I will import that all right so the logger variable is going to be a static instance of the N log logger alright so the next thing I'm going to create then is a constructor now this is going to be the default constructor and it has actually no properties or methods in it so we're just going to create an empty can structure so the next method we're going to create is called get instance and it will return the instance variable that we have listed above so let me put some notes here to see if we can clarify what this is supposed to do so once again this is the singleton design pattern that we're showing and so this function will create an instance of the class a new one if it has not been instantiated yet however if there is a value for the instance then we're going to just tell the constructor hey we've already got one of these so don't create a new one all right so let's go into the code to see if we can do something like well that those comments are saying we should do so we're gonna check to see if the instance is no that means it has never been instantiated if it is null then let's create a new one so that's great and send them back a new value of instance however if it is not null that means someone else already called this constructor and we will return the instance to them so this is the essence of what a singleton will do only one instance is allowed to exist all right so we have a method method here that will get exactly one instance of our object here I'm gonna do the same thing for the other logger variable here called just the logger which is part of the in log system that we imported so I'm gonna do a similar kind of a class or a method here I should say that's going to get exactly one instance of this logger so I'm going to create a private private method here it's going to be used only internally in this class and we'll call it get logger all right so the rest of this code then is going to say first of all let's check to see if this variable is as a valid valid value or not so we'll check to see if it's null then if it is no we will assign it a new instance of it and we're going to use this parameter called the string the the logger and then finally will return this so we're going to use this in just a second so hang on and you'll see where where it fits in so we're gonna go down into these four classes the debug the error the info and warning now they say classes I meant methods these four methods so the first thing I want to do is check to see if this argument value actually is null did someone pass me a value or is it just by default null probably no so if it is no then we're going to go and ask to get a logger and will provide the XML defined property called my app logger rules when I say the XML I mean the the defined properties in law in log config and so we notice here that we have four different choices so obviously we're gonna choose debug to match the debug methods so let's choose debug here so the opposite is the else statement so if the argument is not null so if it's not null we're going to just pass that argument along with it so this is handling two different instances of the constructor that we could use in a logger object so we're handling a no-no parameter for Arg and one that might have a different one now this is going to be repeated all the way through the rest of these so I'm going to copy and paste the code that I just typed and replace it in each of these sections so instead of debug we're gonna put in ever and we'll do that twice all right so each of these gets their own different extension here so ever here matches the method name ever info matches info and so on alright so this is a singleton pattern we're accomplishing the exact same thing that we did before but we're going to have exactly one instance of this logger throughout our program so I'm going to save this changes and now let's go and implement it here in the log in controller so switching over to log in controller this is kind of like changing paragraph numbers or turning a page here so we're changing to a different goal so what I want to do now is I'm gonna just delete this line here because we no longer have to instantiate a new object every time that we use it so that's the that's the goal here of a singleton so the singleton says we don't have to declare anything in a local context like this however how do I get to that logger so I just changed this I'm gonna delete the part that says logger and I'm gonna put in my logger dot and then I'm gonna have to get get instance now you notice it says I have no idea what you're talking about what is my lager so I'm going to go show potential fixes and say I want to use this directory called activity three services utility so let's just click that and utility is the folder over here that contains my logger so it seems to know that that's where it's located so let's see if we can get anything from there now so now I put in a period after my logger and I choose getinstance and then a dot and i can choose info so there we go it's the same same goal producing the same log messages but we're using a singleton pattern so I'm gonna copy this section of this little bit of code here and replace it wherever I see the word logger period so just paste over top and each of those so this one down here is different it has the error connection instead of the info and they seem to work I'm just gonna test it out hopefully I didn't break anything so let's log on log in with a new user okay it looks like the applications up and running so let's go to the log in controller I'm gonna try the same guy ahead earlier as Max and his password is password 1 and it is successful ok so the time I'm gonna check down here the time is 343 p.m. and let's go to the log folder and open this log and look at the time so we have 3:25 it says what is that oh that's the date here is the time 15:43 and it says there was a successful login so it looks like logging still works I didn't break anything at least and so this is a demonstration of how logging is in incorporated into your program so we put it at key points these these logging messages we put them at key points such as a login success maybe we would put in a log message when we create a new order or somebody checks out or somebody finishes a game you can think of pretty much every important milestone in the flow chart of your of your program depends on your program your design of where you put statements about log messages is going to depend on what's important to your program so you and your team will design log messages to be able to do a long term analysis to figure out how busy your app is or how efficient it is so there's logging and a little bit of a singleton design pattern to go along with it so we're gonna do a the next video I believe we're going to do is at rest services so we're gonna create a bunch of JSON data so stick around for the next video if you like and we'll see you soon
Info
Channel: Programming w/ Professor Sluiter
Views: 26,391
Rating: undefined out of 5
Keywords: Logging with NLog in ASP.NET, asp.net loggin, asp.net mvc logging, asp.net logging to file, nlog tutorial c#, nlog, c# nlog, c# loggin, c# application log, Logging iwth nlog in asp.net, asp.net, asp.net logging, nlog setup, nlog example, nlog dependency, C# logging, c# log file, ilogger
Id: PnlxRmHg0lU
Channel Id: undefined
Length: 23min 14sec (1394 seconds)
Published: Fri Mar 27 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.