The log4net Tutorial: Logging in C# (hands-on from beginner to advanced)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Application logging is a big deal. Keeping track of issues in software in production needs a priority of any application developer analyzing what went wrong monitoring the application responsiveness and getting metrics about usage are all important to deliver a healthy sustainable app if you search the web for application logging in c-sharp it brings up a number of options and suggestions if you come down here to the.net logging tools and library, it will give us a list of a number of different loggers. So where do you start well they come back over here to the Stack Overflow questions and answers you'll note that a lot of these in the answers will point to things such as log4net in fact it to go to all of these answers you'll find somewhere in here something about log4net if you like me at this point you figure that now is a good time to try out log4net to see how easy it is to wire up and use in a project and that's where he hit the wall there isn't a lot of great information about log4net if you look at the log4net site which is this right here you'll find there's not a lot of good information here it has documentation but rather ugly and confusing that's why five years ago I wrote an article on log4net for code project after spending days digging through the documentation experimenting in test apps in figuring out the answers to my questions I decided to make life easier for myself and for others I compiled my notes into an article that covers how to set up and run log4net in a production environment since then the article has had hundreds of thousands of readers and continues to generate about 4,000 views each week that tells me a couple things first it tells me that log4net is still a popular logging library and second it tells me that people are still confused on how to implement this library that's where this video comes in I learned best by being shown how do something I figure there are others of you out there just like me so I'm create a video as a companion piece to my code project article I'm going to walk you through setting up log4net for the first time your application you can follow along as they build the application in and then add logging to it. We will start out simple but then we will dive in the depths of what a real-world implementation might look like by the end you should feel comfortable adding log4net into your application lets get started to get started on let's start with a console application this is going to start off with a basic hello world style logging demonstration where do just enough to get logging working the cool thing here though is once we get long working we can actually scale this app out into something that would look like a production have very easily so I start small and build from there so here I sit up a console application I mean that long for net total as a solution and the product name is console you I okay let's go ahead and create this application so here's my basic console application if you're not familiar with console application it looks a lot like the DAS windows of all and if we're at right now is going to pop up a dialog window is going to go away let's instead go ahead and add a couple commands just to have something on the screen first we're going to create the console right line and say hello world and next we're going to say console rely in order to stop the console going away this way the the console and pops up is going to say hello world but I'm gonna pause until hit the enter key let's go ahead and run this year ago there's a hello world application really simple right now just as hello world it waits for us to give us some kind of input we hit the enter key and it goes away the applications done so now adding longing to this is going to take five steps the first step is to go to our references and same ang NuGet packages in here let's search for log for net person that comes up is the official for net new get package heidi is log for net go ahead and install that that's it for step one we go back to references and expand this will see the long for net DLL is being brought in step two is a step that really trip people up ok so don't panic we ever step can look overwhelming but once we break it down you'll see it's not that complicated for step two is to go into our appetite config file this right here now if you're using a web application this was a web config file for our purposes is the same difference if you're a desktop application it's apt ICANN fee if you're in a web applications web.com be the first thing they do in this section is create a section dedicated to log for net surfers can fix actions inside here section blog finance and that made me anything you want but I recommend keeping a log for that type equals blog for net config log for figuration section mendler comma log in at right nor does all that we just need to close it out ok so we're done here is i said im gonna create a section in my config file called long for net look for that alright so now let's create a section called log for now everything in here is gonna pertained to creating a log files wendell log files what information along to how long the great thing about putting information in here is that at runtime we can change the configuration of our logging without having to recompile our application the first thing to add to our long-term debt section is what's called an appender now I pender is basically a logging tool it's what do you want to log to in essence INS we're going to a log right to the console window since we already have a console application it's the quickest way to make sure your feedback and eliminates a lot of problems of do we have permission to file system to have to mention that database is a problem with the connection string all those things go away because it's a very very simple longer or pender so first we give a name again asking me if you want but Scott console appended next the type and this is the Civic so long for net dot appender console bender we're going to look at more Penders in a bit before right now we're just going to use the console pender gonna walk you through how do it later on she had a good documentation and find all different vendors and how to use each 129 define the appender line now you put things inside a pander to the console appender we tell the console how great our message and that's called the layout type equals the long for net dot layout had information that I can put the console but what he want on the console lay down there's more than just the actual message while log for example there might be exception data or the date and time or the long level inside a layout for the consulate hunter we have a conversion better value has to be that pattern you are right out long for now has a specific way of getting a what each item is and we go over all the values could be gonna give you a pretty standard layout first date and they're a specified that should be absolute there are a couple things in know about the state first this is the local dayton time if you want the UTC date he doesn't specify UTC date before the important if you're running long for net on a web application that may be installed on servers in different time zones the second thing to note is that absolute the absolute is a pattern it just tells us dad this is a specific way I'm gonna lay out the date and time you could put your own pattern here but so much slower process for log for net to figure out how layout date compared to using one of their three built-in patterns for dayton time in this case the absolute pattern next let's put the thread and this was just give us these thread number for a currently running thread next let's do the level of the error that could mean doesn't information log or it could mean the error log off a dialogue ranging between finally let's put the message this is the actual message you give the logger and then just in case we have an exceptional augurs well for example say we threw exception want it we want to give it a message we also want to capture that exception information as well we can pass both of those pieces of data together to the logger and in this case right here if we can add something for the exception to be displayed nothing to show up so go ahead and create a new line first and then next up with the exception and no there's no spaces there the percent sign in a case of start of a new tank in so i'm saying read the end of the message for new line and then right away with the exception if there is one otherwise blank and that's it for now is closed our tank and now we have and Pender called the console offender but has a layout that specifies the day the threat number of the threat of where the law was culled from the level of the message the actual message is being launched and then if we have one we're going to put the exception as well all of this information will be written to our Console every time you log a message so that's an appender pender again is just something we're alright the log to in this case to the console you can have more than one up yonder in your long system you can even specify that one appender get certain type of log messages or certain messages based upon criteria give it will get more of the depth and detail those things a little bit before now again we're just going for the very simple tutorial just to get you started then add on to it so we have one of pender but we're not done yet another log for next section the file piecemeal had just called route and in here we need to tell long for net what up hinders to use and then we also can specify the overall level of logging to do so I start with our level of life so level value equals yesterday but what they're saying is that a lot of every message that the debug or higher now there are a total of seven different states for the logging levels of wage which only actually right to five of them the other two are just for our convictions so here I am specifying the debug level that is the the lowest level mean we're betting a log all of our messages where say if it's a debug log if it's info get it was worn logging was an error log get it was fatal to head lying if I said instead debug I said error then I wouldn't long the debug message the infamous age or the warning messages I would only long error and fatal messages so this one setting we can change how our system is working as a production at typically we only while log error messages we need to know the applications crashing or throwing errors that we're not expecting but say we have a machine that's throwing errors consistently with you come on it and machine and wants to running change this log level from air all the way down in debug than all those extra messages that aren't being logged normally will get picked up and put door locks this liquor laws much larger but that's what you want we are trying to track down problem once you're done drinking problem he can go ahead and change log level back to error so this right here is our first look at a filter and we're getting two filters in more detail especially looking at a Penders and the idea of having a pender also have a filter level but for now let's go ahead and changes back to debug one thing I know is I've given you five logging levels have mentioned five debug info war on terror and fail but I said there were a total of seven the other two are all and off so I wanna turn logging off entirely I go ahead and change this to off now nothing is locked or if I want everything I can also say all in debug are very very similar in the fact that both of them along all messages so for right now we have our overall filled their a-level we've sent to debug which would give us all the messages from debug on up or basically all messages the other thing we do is specify that were using the console appender the reason we have a dealer's is because we can have extra vendors and our config they were not currently using so let's go ahead and specify the console pedigree just create do this by saying I pender Dashrath and then press space and ref equals console appender because attack principle that they now here is this console appender gets its information from this name right here remember I said that you can name as athey want but if you do decide to change this name you have to change this as well calling yet console pender makes it very easy to understand that this appender is the console pender with a hard to look back to the offender and then looking the type alright so go ahead and save your apt a config file if you look at now and you first walk in with all this already done it can look a bit intimidating but just remember this just specifies the red have a long for next section in our config file and go ahead and call that this just specifies that we're going to write to an appender ori source to capture our log information inside here we have a conversion pattern this just says here's what the log message should look like and finally we specify by that we need to call that console tender and that the overall filter level for our messages is debug the configs action isn't something that I typically reach he from scratch every time I copy and paste quail bit my previous configs or from my blog for net article remember I said that I wrote that for myself as well as for others I use as my own reference guide because they're fine either go to then keeping notes somewhere else copying and pasting config isn't a bad thing is just important to you know why things are doing what they're doing that's why those pitfalls I see a lot of people do when they first start using log for net dialer config sections say oh my goodness that's so confusing so imma go ahead and copy a working config section from someone else and then paste it in my code cross my fingers and hope it works that's not the wisest choice so that's why waukee third detail step-by-step of each piece this configuration I do expect you to type this over and over yourself but you really should understand what each piece does and why it does it that way when you decide hey my application shouldn't be long anything below an error message you know exactly where to go in this case right here and Zach was changed to in this case error so that's step two RAM we have five steps to implement log for net and step to his private biggest and most tricky step of the mall step three is a comeback to a program that CSS file and we had an assembly reference so under this task and tree in a bit of code assembly cohen's base while Dad config XML configurator watch equals true so it can be a bit confusing but basically this is doing it saying I have been using XML configuration to configure long for net and watch to watch it but the watchtowers make sure that if it changes their updates the logging appropriately so if we have to specify the accident configurator that stands to reason that we could configure log for now and different way and that's true you don't have to do all this config you can configure long for net right insider code without a config file and nothing demonstrate that today because it's a little outside of school board doing it makes things a little confusing especially for new user instead we're going as long as it was designed using XML configuration in the apt a config so this assembly statement needs in your application in one spot and one spot only this just says configure log for net to point that out to think we don't need to do this multiple times so if you're building in winform application or WPF application typically what I would do is put this line where you started your application so look for that static void main somewhere where that is I put this also named space in that same file again this is copy and paste code it's not something you needed change they send your application unless an edge case that step three step four is we need to create inside of our class program we need to create a long reference and what this does is it creates a new instance of belonging system just go ahead and create private static readonly log for net dot I log writes that the type and now we need to give it a name typically I call it long and I say equals long train at laws' manager that get longer now this is going to ask you for your name of your longer this is where people get really confused I say get confuse but they may not actually even know that they're confused the way long for now as designed and you create a longer for each class that you're in you give it a name based upon the class the area so this case I might get programmed ICS is my name that points to this specific class that way later I can look it which program was I in my longest message no point to programmed ICS something gets kids but that they don't want to open more than one login since it doesn't create a problem is thread-safe but if you really want to open one lawyer and since your entire application not recommended but if you do what you can do is just give it a generic name and then passed this instance around to all of your different pieces here application so the most basic thing to do is to give it a generic name based upon waiter at Chili's case programmed at CES now when I change over to new class I have to give it the new classes name and if I had 11 programmed ICSA had one in the test folder then I need to make sure I included the path based upon where it's at so say / program dot CIS and having the test for aids say / test / SES but that means ourselves for each one of your classes there is no way of doing this and that is to use reflection to figure out which class work in and give that the longer to do that we do system flexion method base get current method . declaring tape is long but what this does is it says using reflection of me this now if you'd use reflection on or if you've read anything about reflection you probably have objection radar now is the same one that I have a fresh start in that direction is reflection can be slow so I'm doing this a lot more fun doing this in a resource intensive application this could be a serious problem because some application down significantly enough that it's a concern was a couple responses to that first of all we're doing this once per class so not responding up classes at a very high rates and by the classes I mean classes actually use the logging library unless you're speaking of his classes at a very high rate that reflection is a very very very tiny part of our application in that case is not be a big deal second it makes our application less likely to break in case of change for example what if I aside happened on road after a footlong in Taiwan change denier programmed ICS to be my apt ICIS that would change the class name but it wouldn't change a static string rain here we're now this would pick up that new class name in long as such it may sound each case and really it is but it does make life simple in the fact that I can just copy and paste this exact line into every one of my classes that I need loving but there is a new feature in dotnet four point six then meets the middle of both of these methods and show you that in a little bit once we get the longing working so it's been a long working and they will come back and see how we might go to tweak this to be a little more efficient but yet still be a simple as possible ok so now with credit save and now I've done step for step one was we had that new package step 2 was we modified all the configuration step 3 we add assembly reference in step 4 is we add this long property leases with one step to go to finish out and that step is to actually log something so down here and we're gonna say lawn fastest rate here so if you change the longer it be longer down here so long died in his response if I what type of message logging so I can say long dads error so here I am saying this message whatever it is this is my error message this message is an error I want right to my appender in this case the console vendor so I missed a console right line hello world and then gonna log error to console that says this is my error message let's see how this works run I have hello world and I have this stream right here have my time I had the thread that I'm on I have the type of law to message this case an error and then I have this is my terrorists such know that if we look down here this is my error message that's the actual message gets written now and the rest this information is pulled from the system a South if you go back and look at that conversion pattern we see that date with a thread the LogLevel the message and then we didn't give it an exception information so that's how you use long for a net to write to the console pretty simple but from here we can move on to a more in-depth example natalie have locking working this one thing when I go back dress and that is the section right here where it's the reflection remember I said that we're looking at different way of doing this and this is the one section that's to.net 4.6% pic ok so if you're using the.net 4.5 our previous then you're not able to use this matter I use so if if that's the case continues the reflection or type out your own name here but if you're done at four point six are beyond the headlines create a new class called this log helper class and I'm going to create a new method called public standing long for net died I long it was going to turn get longer now here's the tricky part dotnet four points 6 has a attribute called caller file path now he uses controlled and the using statement for system . runtime . compiler services have been called caller file path and then we give it string filename equals empty string in so what this does is it's an optional parameter and if we don't add something to the filing then I don't fault the car file path attribute takes over and gives us the path to the file is calling this method now has the full path so keep that in mind we are storing information your story a full path or file that also means that if you have two classes in one file same file path for both of them but if he follows standard convention of having one class per file then you'll be fine in here we're going to return that . Log Manager . get longer then here for name in passing by on them and that's it every time I call this get longer method we're going to instantiate a new instance of the longer with this file name of the file name from where this method was called not harassment is located so I see as inaction and come back over here and right now I'm still using the old reflection method of getting my name but let's see where that what that does first base line before we make a change go ahead hit run as you can see we don't have any spot he was telling us where that long messages coming from we don't see a program that CSI we're here so we go ahead and change our vendor to make sure that we're displaying where that information came from go ahead and close this changer pender comeback tour after config and goes conversion pattern right now I'm saying then I want to date the threat it's on the level meaning error info or debug and the actual message and passing it along with the new line the exception if there is one instead of seeing this thread let's go ahead and change this to be the longer the longer is our long source aware that the law is coming from Sophie runs program again we should see the console you I dot program case namespace in the class name for which this log messages error was called network capturing that information to display it let's go ahead and change this to use our stack classes to show first that's coming this out an extra bonus a long healthier diets get longer and that gray simplifies the log call makes it much easier to read and it makes it much easier copy and paste without fear no the best does not allow us to stop the practice of copping this one's per class we still have once per class in order to get them longer need to be changed based on where the law is called from let's go ahead and run us again this time I see something a bit different in sidebar square braces we have the full path to our program dot CIS file what this is doing is it saying this is where the file was when I was compiled so that's a bit different from our namespace . classname we had previous with the council you I dot program but this can be pretty helpful in a fact that is telling us which file to look at when you are looking to debug so for those are you running dotnet four points 6 or above that's an option instead of using reflection now we have longed for networking we're going back through and look at each of our sanctions and expanded into a more full featured section so for example what we're gonna do right now is look at those offenders in the apt I config we start with just one offender it was the console offender that's great for testing and this may even be something you use and production to paying circumstance but probably this is not the only appender you want to use ever so in this section we're gonna expand out what other Penders there are and we are wrapped the section up by looking at the list on the Apache web site dead covers all the different vendors that are available the first opponent is the file appender name given his file appender again that's something you can't blame yourself but for consistency sake I like to keep it similar to the same as the name that long for tickets to the name is filed under and the type is long for net dot tender filed under inside here first thing as he thanked called file with the value of the name of our log file story this on C Colin / logs / my log file that txt and then I say append to file equals true we don't overwrite this one go ahead and enter the file is time and a lot he model type equals by gender file appender + minimal clothes that out what this tells us is that we want to ensure that we can write this long file easily especially from multiple different locations without stepping on toes 30 had trent lott this as little as possible the file through my dad right now is our layout type in this is very very similar to this right here in fact it's the same as up here unless you want change how the layout looks in this case we don't want copy and paste so now the way the log actually print out in the text file is the same as it will print out the command line we could get into changes conversion pattern and a little further on this course we will talk about different layouts and different ways to get information either system but for right now we're going to the same pattern since we're not worrying too much about the layout pattern yet we're just trying to figure out how these different vendors work the last 90 here is we could also add a filter in here to say which type of long statements give written to the text file but we're not gonna do that here talk about filters a little later so we're asking say that everything just launched as long as it passes this check down here where the level set a debug member debugger and higher just logged right now I really like that for a while now so we have now completed our first new appender the file appender before his can see as an action you come down his roots section and add this as appended to be used so tender dash RAF equals file under your spell it right and that should be it let's go ahead and test out this new pender your head and resize this folder open over here to my logs folder and for his starts opens up in my life how is created and we have a message on screen and 24 to go way I wanted it yet because open up this text files compare looks very similar so I have the the time I have the location is case the program that CIS type which is error and this is my error message so will the same ones you sent a text file ones in a console now if I close this out I start over again only have one long message here because it's a new console window open up my log file died txt I have two messages says when the benefits of city to attacks by so that's the file appender now there's one flaw that you may notice with this and that is that this file will grow unlimited because the long run this application to more than get handed us text file it's never clean itself out well this next appended a look at will help us with that was next up under this rare call rolling file type is 14 pender rolling file appender inside here we're still here filename so file name equals C Colin backlash logs / rolling file txt si tend to file value true I say they're rolling style I'll be size so its gonna say that go in new file every time we hit this size maximum file size value equals 10 cents to one source file get a ten megabytes we close out star in the next century AD here is our max size backups in this valuable asset to be five so what this does is it says I want a maximum of five of these up to 10 megabyte files so we have here it is once our rolling file long dat txt hits the 10 major by Mark Wright one more entry into it then a system is going to rename this file rolling file law got txt . one and create a new rolling file logged out txt once that wrong file logged out txt it's the 10 megabyte mark it's going to rename rolling file long time txt 2012 be rolling file logged out txt . to its name the currently full 13 rolling file long died txt doubt one is going to create a new ruling file on that txt once it has buy extra files so we have our cars got one dot to dot 3 Darfur and died 5 when the current ruling filed that txt which is always a lazy nation when that when his ten megabytes drop top 5 gonna kill the file and then made up for us $5 $3 for a list and then makes a new rolling file long that txt your latest day is always in the file you named a rolling file long dead txt the next newest data isn't adopt one and then always down till defy was the oldest daughter you have stored so this case around store ten megabytes in each of those files or have five backup files so once we have a full backup set once you've exceeded our maximum storage capacity we could have anywhere between 50 and 60 megabytes worth of data as it stands right now next we're gonna say more I don't be static log file name is true in this is make sure that the founding doesn't change now last thing I do is copy and paste our layout is it the same and so that's one to get used to how painter's work really is just copy and paste and then we just modify that things that are different for specific offender in this case the file name is the same for both the rolling file appender and a file appender they both have attained co-founding any both have the idea of a pain to file versus over a new file there are some variations based upon the type so little more specific the rolling file appender that does the file appender but basically these offenders are about the same before you go on look at something a little bit different little bit outside the norm for file defenders I wanna go ahead make sure we see this action cases go ahead and safe three sizes again and one last thing before we forget we have to come down to the roots section and add this final fender bender RAF RAF equals rolling by vendor should be good to go more time we had run and nothing seems to happen this is the part of the episode I did call find his mistake and go back and look at our config something is wrong he spied a year pursuing you may pick up really quickly for others it may take longer but you look here remember I said he's a similar this appender and this appender have a lot of similarities there lay out the same the files the same but look up here in such file value equals and down here file name equals I was talking while typing and came out as name instead of value was tries again run and now I have a ruling filed long dead txt called out and look at our file long it looks very very similar to our list just now this one has one entry whereas this one has multiple alright so that is the rolling file under very similar to the file appender I would recommend however that if you're going too long to text file that you use the rolling file appender you don't get burned with a server that clogs up with a massive text file even here fairly certain he'll come back to that file and get rid of it everyone so I'll make sure it stays small you really don't wanna help file they can grow without end so I get rolling file tender and always just keep it delete old files that way if you don't get to something or if you get an error in a loop and just keep spinning up issue after issue long in the log file you don't shut down your computer or server this next appender can get a bit tedious to type out your head and copy and paste a walk you through each thing does start out with the appender name equals ATO net offender and a type that under 8000 under all rights in here based in my code and that's a lot of course let's go back and look at what does the very first thing while Jack is the buffer size the ATO dotnet gender rights to any radio data source in this case writing the sequel server so this right here is one of those guaranteed thing that will trip if you copy and paste someone else's config I have seen a number of questions from people either on Stack Overflow our code product or elsewhere were saying my ATO dotnet appender does not work I've tried it I tried the text layout and it works I tried to rolling tax it works and I come to ATO and nothing works always comes back to are almost always comes back to this buffer size so what this buffer size is it a sad instead of writing a query to sequel server every time we have a long message to wait until I bill a buffer so in this case after 10 log messages have been written on your right all ten of those two single server and that just keeps the traffic down a single server the kicker here is by default whenever you see a demonstration on line or even at the long for an essay that if it will be hundreds you have to write a hundred log messages before any of them show up in your single server now when you do close out your application though supposedly written to single server so if you're watching us applications open you may I see anything we close it you may see those ten twenty thirty long messages written a single server at that time my recommendation for demo purposes is that you set this to one that way every time I log message gets ripped the server you see it in highlighting times it may put extra strain your single server but nothing that it's not able to handle the production values in private much higher than this but we're really depends on your scenario for instance if you rely on up to the minute reporting on your errors in the logs then erosion have this is lowest possible maybe even one because if a system does not write a long message very often and you have a 608 maybe hours or even days before that buckets filled up waiting days to find out the you have an issue is not ideal for demonstration of keepers at one the next thing is our connection type in this says hey we're use a sequel server connection and feel free copy and paste this this is a whole bunch of stuff that no-one memorizes next we had a connection string and this just says helicopter database in this case and cut into the local database or dot the catalog amusing is my my database itself that's application to be and then using the integrated security which means it going to use my login as the security from a single server next is the command text this is the actual query to run in this case let's get down to hear the command typist text that means I'm running a raw sequels to in this case an INSERT statement so i'm saying insert into the table logs here's the columns to use and then here's the values to put in them now there is an alternate that's much easier to do in this file is also in my opinion better practice and that is to use a stored procedure so instead these two lines are living here for now to show you a difference but you would play its command text value would be the store procedure name and that's it and and the command type the value equals stored procedure so you wouldn't put both of these in here this one and this one you choose one so either had a like that where you had it like that personally I like this method better because it's so concise out to type all this out I can also do things are stored procedures such as having extra statements around my insert or making an upsurge statement so that if it's already a statement there that matches this which shouldn't be but if there is we could do an update 7 answer there's a number of things we can do in store procedure but size just the actual insert but I use it is up to you so choose used or procedure or the actual command text go ahead and take this out both work the same way so I can you demonstrate both big deal both work against you for your call I'm gonna show you one more thing and that is the parameters right here these match up to these parameters down here now in a stored procedure takes parameters and their named just like this but we don't you specify them because they are specified for us but for the INSERT statement whereas just taxed I have to specify the parameters so that is one thing I know is that we have to actually specify the parameters passed in in weird again passed in alright let's back out so we have a number of parameters down here let's go through them when they won the first parameter is the at log underscore dates between specific parameter name that D be type in this case it's a datetime tape now this is a C sharp type not a sequel type so no this DateTime not daytime too was when I actually story in in the database next is the layout this looks very familiar if you're looking up here was there is needed this only instead during the pattern layout I am doing the wrong time stamp lay out the timestamp for his log entry and so instead of specifying the conversion pattern here it just knows ok you're at the time stamp on give it to you that is a bit of a deviation from what we're doing up here we could do that we could take us out instead put a layout that uses the percent date absolute but that's a lot of the DVD a little bit and show how it looked a little bit different our next parameter is the at log underscore thread and this is a type in see strength now in CString identifies bar chart if you're familiar with sequel is to type of string feels akin story there are two major types the first type is March are annexed is nvarchar bar chart is a variable-length strength whereas in March are is still available thanks drink but it can store Unicode characters in this case I said I don't think I need to store Unicode characters in my database therefore I'm they use large garfield's and so we have to passing and C string as the type if we were storing nvarchar are considered an CString we would just do strength so that's the difference the size is the size in our database in this case of 50 characters and then this should be layout pattern just like up here to lay out pattern can be very complex plots this is the layout pattern for one field I'm storing each field in a separate column therefore it's very very simple here I'm just story but thread to come down here to the next item we have log level it's an ancestry as well against it the characters in this just stores the level and that's our debug error warned fatal or involve the next one log source that's the location with a longer in it and so I made that 300 characters long and the pattern is just that percent longer next we have actual message this is what we send when we call log and still industry and its four thousand characters very large but you make sure that benefit you could do in March our Macs which is much larger if you want you but in this case I say you know what 4000 characters is planning to that's about shoes and find out here we have the exception against ring again 4000 characters and the layout type instead of being one of these items i'm saying give me the exception layout so these are the fields and inserting into my store procedure note that we don't have to put just 11 a.m. into anyone field and we don't have to use it just once so you could get creative in here where maybe you rate each item to its own column but then the end have a column that is the printed lawyer what you would see a tax policy like backwards the combined file what you write the database is totally up to you used to make sure that your INSERT statement or your store procedure will take that information and so speaking of stored procedures let's go ahead and look at our store procedure first here's my table this is the logs table its me application TV and I have I D along date with red the level the source the message and the exception so I did know the varchar sizes match up with what we have in our web config file next I create a stored procedure that takes those same names and inserts them and there's an INSERT statement does nothing different than what we originally had with the INSERT statement for the command text but now I have it wrapped in a stored procedure finally if you come over here to this window I had a slow start from logs if I run this I see that have no entries so far let's go ahead and change that will come back over here we come down here to our roots section and add this appender and that's double check that insurance rate ADR net under so we should be good let's run us I have message on the screen but come back over here to sequencer I R us again I now have one entry date there's a date and time there's a thread number there's the log level there's a source it came from and there's the message and we don't have exception so in just a few moments we were able to use this pattern to write a sequel database now we're starting to get into things that can be more useful in a production environments now we have to arrange a single server let's look at other options for radar data if we go back to the long for next site logging . patchy dot org / long for now we come down here the SDK reference there's this long for net appender and you know every time we have created pender it's always been lost for net pender . something so go ahead and open that up and as a whole list of things in here and we look down here we have these file appender class and it will tell you all about the file appender it's not great but it is something and you some clues as well do it also gives you an idea that you can do a file appender which we already knew but there are other painters and here you might not have known about for example the ANSI color terminal appender I've never used that there's also the buffering appender skeleton buffering 14 pender may not useful for you and your case but there's others in here that might be for example there's the eventlog appender this rights to the windows event log it's something that sounds great but I would recommend against trying to use in too many situations there are situations where it's right but the most part it's not great in the reason I say that because you have to have special permissions for the use of its running this application so if this is a web application typically you're running under the asp.net account if you are under that account you either have to change the permissions that account which I don't recommend in order to get more rights or you have to write to the event log once using in mister account in order then kind of allow that to be written from then on using the asp.net account its little clunky but it does have its purposes another one it has its purposes that maybe a little clunky for you but it may be perfect or somebody else is the SMTP appender this will allow you to send emails out whenever you have a long feiler in my advice here is to make sure the only sending emails out when you absolutely need to don't send emails out saying yes I got this piece of code especially if it's a little especially if you're saying that your boss this is just one more wave it you can do something with technology that you probably shouldn't so I would encourage you to look through here look very different vendors find ones that maybe you want to use or that fit your certain scenario where you think they might and then go find examples of how to use them and there are examples in here if you come down to configure examples we can scroll down find there's the MS Eagle server example isn't access example both he's an ATO net appender in this case the access one versus the generic one for the single server is Oracle Oracle as a whole bunch more in here and you can go through and not only see ASP net race offender but also how to use it if we come back up to a single server one you'll note that the buffer size is set to a hundred so as make sure that you take whatever information you get in here with a grain of salt it may be a valid setting but may not be the same that's right for you in so that wraps up our section on tenders we've gone through identified each of the major types of tenders and also where to find out more information about other alleged case of vendors Nextel look at filters if we come down here to the bottom we have this one filter it says only give me items from deep above but they're more houses we can add to our panders to limit what information they get so let's get to that now before you get in a setting up our filters I want to a little bit of housecleaning first let's go ahead and collapse over a Penders Lee better-looking file here only the console appender open and we're just going to use the console for now let's go ahead and comment out these other three offenders from me used no I'm just commenting them out from the roots action I don't need to actually change the offenders themselves if an appender isn't mentioned in as root section then it won't be called for now and just the console offender here I have just the console penned up here let's come back to the program dot CIS and let's make a few changes here in order to have more log statements person to leave the ones we have and then start creating new ones say long does debug that's the lowest level message so far this whereas a developer colon tutorial was right next let's do lawn dads info is the next level up it will say maintenance water turned on next law that one says it remains as well and will say the wire is getting hot now for the long . error which the next level up but actually create an air bar equals 0 do a try and make this divide by 0 exception and here if we throw a divide by zero and do a long day error is happier can be involved want to debug if you want it just makes sense logically usually if you're throwing an error and error thrown you that you call an area long statements again it's up to you if you want say it's only for debug or this error message isn't a bad one that's fine in his case was calling Dr message and then here actually include the exception to this is one of those things that I told you about but you haven't seen yet and that's the idea of him pass exceptional long as well back over here after I can we have this new line and then the exception and so far has been black but now we're actually use it so that's a reception let's go ahead and create the exception by saying they are X equals 10/10 since I 0 exception last and highest only long scale is along that fatal explode ok I have five log messages in increasing order of severity so from the blog the lowest involved in Warren an error then they'll first let's make sure they all run alright I have a bit of a mess here in the reason why is because I'm logging out this very very long path to a program that CIS so what's changed that lets get back the reflection method was once again and now it's a lot better it's a little shorter in fact you can trust message down even more so let's go ahead and go back to our apt a conviction say you know what we're gonna I just as conversion pattern to only give us the level and the message where the interconversion patterns more in the lab pattern in a little bit before now we can just tremendous message make a little simpler again and now we have a little better system we have debug info warning error and then underneath the air we actually have the exception and has fail so since you haven't seen accession before let's look at it we have the airline says developer we try to divide by zero again we have a new line and now we have exception message exception is system . divide by 0 session attempted to divide by zero and then just leave whereas at 125 in the program to ICS so I can be really great debugging information for when you have an issue since we just want the actual information on the screen now let's go ahead and take out the exception we know can do it we don't have to do it again and now we have a very clean screen that has just five things on it and in the order from debug their fatal that's a great setup for teaching us how to filter out different items there's a number of different ways we can filter defender we're gonna touch on the most popular the most used and then there are some extra ones we can go look at later on the documentation so let's start by creating section called filter the first built around do is the level range filter so type equals one for her that level range filter and this has 2 entries in it first we have the a-level how is blank for now and then we have the max now leave it blank as well for now so little man and a level max are be brackets around which you want to capture your blog entries remember that debug is the lowest in fatal is the highest so if we only want to capture Warren and error messages the low the men will be warned and then max will be error what this says is has released a warning level and it can be any higher than error message which means that we're not going to capture the debugger info and we're not going to capture the fatal what's runs and see how it works merry go we have worn and we have error but that's it the rest of them don't get along just console instance right now the console is the only appended it's actually logging they didn't get along that are at first that may sound bad thing you're longing messages that don't get captured anywhere but think that one through four minute if you put a bunch of statements in your code that are long done debug and it only for debugging your application you don't want those debug messages story where most likely unless you have a problem then you coming in here just your filter to say yes give me debug messages so we can justice again if you want if you wanna include up through fail because change the max the fatal and now we have three statements war on terror in fatal so that's the level range filter this is one of the few filters that if it does not fall within its boundaries the log message does not get written imma go ahead and comment this out and create new filter that way you can see how each filter works in my code to create a new one in this one is going to be filter type equals 14 net dot filtered through a string match filter so that's good I do it in a match the string pattern inside of our log message so string to match value equals and let's say has maintenance to now only maintenance messages with a lot right we'll find out and we had a lot more than just minutes messages if we look through as managers we see no reference to maintenance in the error or the debug message and yet all five are showing up why is that well remember with the range I said this is one the only ones that if the message falls outside of that range it does not log in this case it matched maintenance on three of those entries before the other to it didn't match and it fell through to the next filter since there are no more filters it assumed we want to log it seems counterintuitive because it feels like we want to not include something if it didn't matter shelter but the reason we do this is because you can have more than one cell filters inside of an appender but if you want just match on this filter you have to create one more filter at the end of type filter that mean I thought there was nothing inside this is the if you get here you are done don't log so now it's going to match the maintenance training and it doesn't find it is good I dropped out of the next filter the next order says don't log was stress again ok now we only have three statements and all three are making statements you should also tell you something important about the filters order is important it matches against the first filter if it doesn't match it will typically drop down to the next filter the exception being the level range doctor if it doesn't match here it's done so that means if I move this filter the denial felt there above the string matched filter iraq again nothing that's because the first built in a match was this deny all filter so it's moving back down to the bottom the next filter we want to go ahead and comment this one now next filter that I'm law internet filter . level match filter this is very similar to the level range filter except its matching on a level surface level to match value equals error this is only going to grab the error level but it does fall through just to stream matched filter which means that we have to continue to have this than I are at the bottom but see it in action all right there is just the error message let's get a little more tricky and create another level match dr. copy and paste this and say I only want debug messages so now I have all the care and debug remember these fall through so it's not an error falls down the next one it says are you debug its runs again and now I have two statements the debug statement and the areas that there might be times when you wanna captured two of the five and they aren't right next to each other so all debug messages but also failed messages as well so as you can see their main different ways we can configure our filters to pull out exactly what we want from any situation next week I'll look at the lawn patterns the information actually write out to the database would tax file the screen will look at the different pieces of information we can pull from a system in a drawbacks associated with gathering back information now let's dive in that logging pattern the strength gets printed out a screen or get store the text file right now we have just the level and the message and then new Lion exception in our conversion pattern or that logging pattern let's go ahead and clean up a couple things here first before we make some modifications to this first go ahead and comment out all these battles go ahead and move them we don't need any more so since have removed all my filters everything will get printed out now know we still have this down here that says debugging higher if I change this to error it only print out error and hired even though I don't have built up here just demonstrate right now I run this I have all five messages my debug info warn error and fail but if I change this to say error iraq can only see the air and fatal message for our purposes let's go ahead and change it one level higher cause a fatal now only capturing one message just that fatal message saying the water pump exploit that's good enough for testing purposes because what we're going to concentrate on is this conversion pattern now you've already seen the standard pattern so for example the date the longer the level the message the new line and the exception is a pretty standard and trees as a few more standard ones for example we had at one point the thread but it's a few extras we can add I'm gonna use the new line after each entry so we know what we're looking at first legal level here with us a level and then put new light at the end of next year as a message that we're at take out exception that gets a start we run that we now see levels fatal and message is maintenance water pump explode now we do have an extra space there was take that out again we should see one per line laid out nice so it's a few extra things one line per time so we know we're looking at the next one is the UTC did put UTC date and we'll do that well this is just like the date only as in if the Utd compare this was put a new line and then put the date certain date and make their absolute well okay so we have the UTC day and the record date as go ahead run us now for comparison we have the level message would be recovered the UTC date is 05 3943 the date is 01 3943 so I'm four hours off of UTC time next let's add the timestamp this was a bit confusing for people not quite sure what what information is giving them in this case 149 its rise again announced so what is that well I am put the new line of go ahead and put them in their first before you start talking about it and that's 110 so what is that times there were times them is the number of milliseconds since the application started their situations that can be very useful now is when we get into the deeper waters the things that aren't as straightforward or aren't as efficient these things so far fairly efficient when it comes to rain to the law new line and we're going to add two new pieces of information first one is the identity in a square poll from the principal denied any dat mean property and the second one is the user name that user name polls from the winner's identity property so these to rate here can be a bit slow and they can also sometimes give you non information or be empty let's go ahead and run this second CD identify mind is blank and yet the user name is office tower / team was that's my login name sort of paying environment this may be great information or it may be non information so just be aware that might not always show up the way you're expecting it to this is doubly true we're talking about a web server remember that this application runs typically on the ASP net account in that case username will probably be ASP net username not the name of the user login next there are few entries they can pinpoint where in the code we had the problem first let's look at the location and this is the location the code where there's a problem now in order for the system know this you have to have the debug information it works a lot better and debugging that was in the production environment just the line number same thing here as far as working better and debug and doesn't production and finally we want to pull the method name again seems cleaner so in this case since I'm running in debug mode in Visual Studio it knows them running from programmed ICS it knows on line 32 and the method is the main method these last three can be very very useful when you're debugging just be very clear that this is going to work great in debug on your machine going into production you may find non day here you may find it empty may find information it doesn't quite make sense because it doesn't have the reference to pull from the right locations so that's a brief overview of the more advanced I am so you can log beside the on the RT covered but we're not quite done yet we also have the option to pad or shrink down our information remember we're adding information to database we said that a log message shouldn't be more than 4000 characters or that exception information shouldn't be more than 4000 characters what would happen if we had more than 4000 characters that be a problem trying to put that into the database well long for now has an option for that if we come back here lets choose the message itself unless it a message should only be five characters long now that's obviously not a real-world scenario but that will give us an obvious to the matter we say topped 5 that dot 5 indicates that the message at most g5 characters if it's more than that it's gonna start trimming off from the left as an action so my message is LOD ok that's the part of the word for exploded the reason is hello dee dee and not mhm TV was at the beginning of the message that's because we capture the end of the message everything else is trimmed off so if you go over your five character limit in this case the first part of message kids to lead that isn't something you can change a setting that's one of those things that could be done all better in long for now I would like it where you would add the first part of the message and then trim at the end but that's a nigga do in code or even make a interface for your log message that goes ahead and trims off the end of it it's definitely doable is just not something that's built in to be done with 14 that ok there's a couple more options we can do here we can put numbers before this died in this would be the minimum number of characters so if I puts in here a minimum of 20 characters and a maximum of five characters what is going to do is is going to trim off anything 15 characters but if it's less than five characters say it's one character it's going to add a space in that space is going to go and the left hand side of your message so if I had just an each in a sealed its gonna be space age because I have that too there if I had yellow exclamation point because it's six characters it was say hello E L L O exclamation point so those two can work in conjunction with the spacing if I instead put a negative sign from it that's going to put the spacing at the end so again might just in each in that message it would be each space inside the space age so if you doing a space to limit text file you could make sure that your minimums and maximums of the same and then anything less get spaces anything more gets cut off and that's all there really is to logging information out to our file a layout that we like that's the conversion pattern now have a handle on all the information that long for net provides forest and hits log messages let's take a look at how we can bring in our own information when we talk with the advanced features of luck for now sometimes we are logging in log for net you just want a little bit of extra information you could bring in the message but maybe why and different field or maybe using that ATO dotnet appender where you want put in different column if that's the case there is a way to bring information in let's start by cleaning up our conversion pattern here let's just do the message itself looks ok we just have maintenance water pump exploded that's fine for now let's go over to our program and we have these five messages only this one is being pulled because it's a fatal message and that's the only ones that we're pulling in using this long level so let's create a loop down here in here and do a for loop yes a 12 lasted five which means zero one two three and four so it's five till now just and we're going to say long . fatal this is message number and the eye of the end and actually we're gonna change that from something different because we're already using I up here or just take away the declaration has already is okay so we have I 0 ice less than five as long as five messages we can go ahead and commenters out so now we have five failed messages that say this is message number zero one two three and four runs and find out okay so you have this is message number zero one two three and four well maybe we don't want to have that in the message itself maybe I say something a little more generic like this is as a fatal error in the process and may want capture that that I information somewhere else the way it do this is to use the properties of water for now we come here and say long for that God global context and there are multiple contacts there's the global contacts in this thread contacts and go through a list here and see all the different contexts a logical thread context these are all scopes so the tighter the scope the more likely it is to be captured so for example if I have something a property name in both the global scope and in the logical thread scope then the logical thread scopes variable is over right what's the global scope that can get really complicated don't worry about it if you don't know which scooped you want use a global scope that will work across the entire application the smaller ones are for specific threads typical so as to you global context . properties and now you can specify or own property let's call this property the counter property and we're say this equals the current diet I know we can put any kind of strange information into this property which also put other types of David in here and we'll get to that in a minute before right now we're going to store I and that's it we don't actually change our log message because we have now created new variable we can pull in in this conversion pattern so let's go ahead and pull out in so instead of having it in a message I'm going to say the number dash the message so let's start with our percent sign and then we save property and they get the name in our cases counter creators so we have percent property curly braces the name of your property but when you called it and I'll put my dash here and that's run this so now I have zero one two three and four within the dash and then the message is a big difference because I could have put that in the message itself but the difference is I now have this as a separate property I can pull in different way so I have made a deal yet tender I can put that in different field now we're done here is just past the value of and I dot toString got the information is stored as text but there is a way to have I don't panic property so let's set that up and over here and create a new class and I call this class the counter class public and one profits into property call this counter so it is going to store the information that loop so I 01234 will store all in this number here and last night to a public override string toString and returning the base that strength I mean to say that I want the loop counter to strength so whenever you call this class and say . to string a class instance instead of returning the class name which is standard for a class instance it's going to return the string value of the loop counter into variable so can save that come back over here too are programmed at CES declare and new variable called counter recall this hour I asked OJ since we haven't I J equals new counter next move out this global context out of my loop and pasted up here when I was in my lube it reassigned as property every town went through now and when I say it once so instead of assigning it a variable was just in a science jay jay is the instance of my counter class now whenever J changes the two string value is remember two strains actually just that loop counter wherever it changes its going to change the property and long for now shut down here I make things a little messy don't do is in production Jade outlook count equals zero and then Jade Luke hour or less than five and then Jade care plus plus sorry place that I variable with the property counter using my instance call Jay that's all I've done I've moved this outside of my lips are only get a signed once its rise again and there you go it looks like nothing has changed except in only a sign that property once it picked up the changes using that toString method so great right as it is this is definitely a test just show up where can do but what this demonstrates is that you could create some sort of property or some sort of class instance they captured information or send information to log for net based upon certain circumstances in your application dan you justice it once in that global context and in your configuration you can pull that property over and over and over again and will always get the latest information a little more advanced it's not something you use an every application but where you want it it can be a great help so they are a couple ways you can get the most out of your long for net using some advanced logging techniques now let's review what we've learned and see where we go from here so that's the basics and the more advanced topics of long-term debt really once you break it down it's quite simple we started off with those five steps to get long for networks first adding our reference using nougat too long for net application next we went into our program dot CSN add this entry right here which is once per application then we add this team right here which happens once per class or once per time you want to instantiate you don't have to once per class if you don't want to end then we moved on to creating this config section so we created this section regular says hey I'm along for next section and then in that long brunette section we add our vendors some with filters some with different conversion patterns then we came down here and add our roots section which points out which offenders are working and then with the overall filtering level is finally we create these long statements that log information to log for net as long as it accepts them to wrap up we create some advanced data too long to our long for instance we create dynamic property using our class instance allow us to our can fix it pull the information dynamically based upon the point in time it which was called so that's long for net very very simple at the end of day you just want to create these long statements you pepper these throughout your application where you need them at the level you need them since he know how to filter and how to limit which long statements get logged to your lawyer appender source will it be the text file database or even a console window you can mix and match and play with these things for example you may have a console window you don't care for scrolls like crazy and see send all her did to it where you have your single database the protect a little more and he only rate warnings above and find that text file which might be a backup for your single server but you only want to write the exception data errors and the fatal injuries he may say you know what i mean a rolling file because it's just a backup and I want to only keep a hundred megabytes words of miles across 10 files based on what we've learned this course that's definitely possible it's possible using the example we've already done just to recap this video is a companion piece of the article I wrote on the log for net tutorial so all the information we've gone over here in this video can be found in some format in this article so if you want the written copy of it go ahead and go here if you want more information from a source you can go to the apache log for net site and get the SDK reference or the how to's or even conceive examples for dependency you want that's really all there is for long for now I encourage you to play around try things out build a dental out and then once you have your config file the way you want to go ahead and convert any production use these things whatever you want to capture information inside your running application down the description you will see links to always different sites you will also see a link to the gift of a positive re where all of the code I went through in this course is start if you look you'll see that the code has been tagged at various levels for each of the different sections in this video you can download code back to where it was at that specific section also if you like this video if you want to find out more information on other providing both here on YouTube in other places as well go ahead and sign up for my newsletter I don't spend a lot of emails out the way do I tell you about the new and upcoming courses than creating and I also ask for your feedback I love hearing from you what you're looking for your feedback shapes these courses so please let me know what you'd like to see next thanks enjoy using log for net without being afraid that config file
Info
Channel: IAmTimCorey
Views: 168,639
Rating: 4.9462533 out of 5
Keywords: .net, c#, log4net, appender, examples, tutorial, logging, Visual Studio, Software (Industry), C# (Programming Language), Tips, training, code, academy, school, iamtimcorey, log4net c# tutorial, log4net c#, logging in C#, tim corey, c# log4net, c# logging, c# tutorial, C# training, c# code
Id: 2lAdQ_QwNww
Channel Id: undefined
Length: 97min 45sec (5865 seconds)
Published: Thu Sep 03 2015
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.