Breaking News
Loading...
Sunday, January 3, 2016

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

3:03 AM

Application logging is a big deal.  Keeping track of issues in softwarein production needs a priority of any application developer analyzing whatwent wrongmonitoring the application responsiveness and getting metrics aboutusage are all important to deliver a healthy sustainable app if you searchthe web forapplication logging in c-sharp it brings up a number of options and suggestionsif you come down here to the. net logging tools and library, it will give us a list ofa number of different loggers.  So where do you startwell they come back over here to the Stack Overflow questions and answersyou'll note that a lot of these in the answers will point to things such aslog4net in fact it to go to all of these answers you'll find somewhere inhere something about log4net if you like me at this point you figure thatnow is a good time to try out log4net to see how easy it is to wire up and use in aproject and that's where he hit the wall there isn't a lot of great information aboutlog4net if you look at the log4net site which is this right hereyou'll find there's not a lot of good information here it has documentationbut rather ugly and confusing that's why five years ago I wrote an article onlog4net for code project after spending days digging through thedocumentation experimenting in test apps in figuring out the answers to myquestionsI decided to make life easier for myself and for others I compiled my notes into anarticle that covers how to set up and run log4net in a production environment sincethen the article has had hundreds of thousands of readers and continues togenerate about 4,000 views each week that tells me a couple thingsfirst it tells me that log4net is still a popular logging library andsecond it tells me that people are still confused on how to implement thislibrary that's where this video comes in I learned best by being shown how do somethingI figure there are others of you out there just like me so I'm create a videoas a companion piece to my code project article I'm going to walk you throughsetting up log4net for the first time your application you can followalong as they build the application in and then add logging to it.  We will start outsimple but then we will dive in the depths of what a real-worldimplementation might look likeby the end you should feel comfortable adding log4net into your applicationlets get startedto get started on let's start with a console application this is going tostart off with a basic hello world style logging demonstration where do justenough to get logging working the cool thing here though is once we get longworking we can actually scale this app out into something that would look likea production have very easily so I start small and build from there so here I situp a console application I mean that long for net total as a solution and theproduct name is console you I okay let's go ahead and create this application sohere's my basic console application if you're not familiar with consoleapplication it looks a lot like the DAS windows of all and if we're at right nowis going to pop up a dialog window is going to go away let's instead go aheadand add a couple commands just to have something on the screenfirst we're going to create the console right line and say hello world and nextwe're going to say console rely in order to stop the console going away this waythe the console and pops up is going to say hello world but I'm gonna pauseuntil hit the enter key let's go ahead and run this year ago there's a helloworld application really simple right now just as hello worldit waits for us to give us some kind of input we hit the enter key and it goesaway the applications done so now adding longing to this is going to take fivesteps the first step is to go to our references and same ang NuGet packagesin here let's search for log for netperson that comes up is the official for net new get packageheidi is log for net go ahead and install that that's it for step one wego back to references and expand this will see the long for net DLL is beingbrought in step two is a step that really trip people upok so don't panic we ever step can look overwhelming but once we break it downyou'll see it's not that complicated for step two is to go into our appetiteconfig file this right here now if you're using a web application this wasa web config file for our purposes is the same difference if you're a desktopapplication it's apt ICANN fee if you're in a web applications web. com be thefirst thing they do in this section is create a section dedicated to log fornet surfers can fix actions inside heresection blog finance and that made me anything you want but I recommendkeeping a log for that type equals blog for net configlog for figuration section mendler comma log in at right nor does all that wejust need to close it out ok so we're done here is i said im gonna create asection in my config file called long for net look for that alright so nowlet's create a section called logfor now everything in here is gonna pertained to creating a log fileswendell log files what information along to how long the great thing aboutputting information in here is that at runtime we can change the configurationof our logging without having to recompile our application the firstthing to add to our long-term debt section is what's called an appender nowI pender is basically a logging tool it's what do you want to log to inessence INS we're going to a log right to the console window since we alreadyhave a console application it's the quickest way to make sure your feedbackand eliminates a lot of problems of do we have permission to file system tohave to mention that database is a problem with the connection string allthose things go away because it's a very very simple longer or pender so first wegive a name again asking me if you want but Scott console appended next the typeand this is the Civic so long for net dot appenderconsole bender we're going to look at more Penders in a bit before right nowwe're just going to use the console pendergonna walk you through how do it later on she had a good documentation and findall different vendors and how to use each 129 define the appender line nowyou put things inside a pander to the console appender we tell the console howgreat our message and that's called the layouttype equals the long for net dot layouthad information that I can put the console but what he want on the consolelay down there's more than just the actual message while log for examplethere might be exception data or the date and time or the long level inside alayout for the consulate hunter we have a conversion better value has to be thatpattern you are right outlong for now has a specific way of getting a what each item is and we goover all the values could be gonna give you a pretty standard layout first dateand they're a specified that should be absolute there are a couple things inknow about the statefirst this is the local dayton time if you want the UTC date he doesn't specifyUTC date before the important if you're running long for net on a webapplication that may be installed on servers in different time zonesthe second thing to note is that absolute the absolute is a pattern itjust tells us dad this is a specific way I'm gonna lay out the date and time youcould put your own pattern here but so much slower process for log for net tofigure out how layout date compared to using one of their three built-inpatterns for dayton time in this case the absolute pattern next let's put thethread and this was just give us these thread number for a currently runningthread next let's do the level of the error that could mean doesn'tinformation log or it could mean the error log off a dialogueranging between finally let's put the message this is the actual message yougive the logger and then just in case we have an exceptional augurs well forexample say we threw exception want it we want to give it a message we alsowant to capture that exception information as well we can pass both ofthose pieces of data together to the logger and in this case right here if wecan add something for the exception to be displayed nothing to show up so goahead and create a new line first and then next up with the exception and nothere's no spaces there the percent sign in a case of start of a new tank in soi'm saying read the end of the message for new line and then right away withthe exception if there is one otherwise blank and that's it for now is closedour tank and now we have and Pender called the console offender but has alayout that specifies the day the threat number of the threat of where the lawwas culled from the level of the message the actual message is being launched andthen if we have one we're going to put the exception as well all of thisinformation will be written to our Console every time you log a message sothat's an appender pender again is just something we're alright the log to inthis case to the console you can have more than one up yonder in your longsystem you can even specify that one appender get certain type of logmessages or certain messages based upon criteria give it will get more of thedepth and detail those things a little bit before now again we're just goingfor the very simple tutorial just to get you started then add on to it so we haveone of pender but we're not done yet another log for next section the filepiecemeal had just called routeand in here we need to tell long for net what up hinders to use and then we alsocan specify the overall level of logging to do so I start with our level of lifeso level value equals yesterday but what they're saying is that a lot of everymessage that the debug or highernow there are a total of seven different states for the logging levels of wagewhich only actually right to five of them the other two are just for ourconvictions so here I am specifying the debug level that is the the lowest levelmean we're betting a log all of our messages where say if it's a debug logif it's infoget it was worn logging was an error log get it was fatal to head lying if I saidinstead debug I said error then I wouldn't long the debug message theinfamous age or the warning messages I would only long error and fatal messagesso this one setting we can change how our system is working as a production attypically we only while log error messages we need to know theapplications crashing or throwing errors that we're not expecting but say we havea machine that's throwing errors consistently with you come on it andmachine and wants to running change this log level from air all the way down indebug than all those extra messages that aren't being logged normally will getpicked up and put door locks this liquor laws much larger but that's what youwant we are trying to track down problem once you're done drinking problem he cango ahead and change log level back to error so this right here is our firstlook at a filter and we're getting two filters in more detail especiallylooking at a Penders and the idea of having a pender also have a filter levelbut for now let's go ahead and changes back todebug one thing I know is I've given you five logging levels have mentioned fivedebug info war on terror and fail but I said there were a total of seven theother two are all and off so I wanna turn logging off entirely I go ahead andchange this to off now nothing is locked or if I want everything I can also sayall in debug are very very similar in the fact that both of them along allmessages so for right now we have our overall filled their a-level we've sentto debug which would give us all the messages from debug on up or basicallyall messagesthe other thing we do is specify that were using the console appender thereason we have a dealer's is because we can have extra vendors and our configthey were not currently using so let's go ahead and specify the consolepedigree just create do this by saying I pender Dashrath and then press space andref equals console appender because attack principle that they now here isthis console appender gets its information from this name right hereremember I said that you can name as athey want but if you do decide tochange this name you have to change this as wellcalling yet console pender makes it very easy to understand that this appender isthe console pender with a hard to look back to the offender and then lookingthe type alright so go ahead and save your apt a config file if you look atnow and you first walk in with all this already done it can look a bitintimidating but just remember this just specifies the red have a long for nextsection in our config file and go ahead and call that this just specifies thatwe're going to write to an appender ori source to capture our log informationinside here we have a conversion pattern this just says here's what the logmessage should look like and finally we specifyby that we need to call that console tender and that the overall filter levelfor our messages is debug the configs action isn't something that I typicallyreach he from scratch every time I copy and paste quail bit my previous configsor from my blog for net article remember I said that I wrote that for myself aswell as for others I use as my own reference guide because they're fineeither go to then keeping notes somewhere elsecopying and pasting config isn't a bad thing is just important to you know whythings are doing what they're doing that's why those pitfalls I see a lot ofpeople do when they first start using log for net dialer config sections sayoh my goodness that's so confusing so imma go ahead and copy a working configsection from someone else and then paste it in my code cross my fingers and hopeit worksthat's not the wisest choice so that's why waukee third detail step-by-step ofeach piece this configuration I do expect you to type this over and overyourself but you really should understand what each piece does and whyit does it that way when you decide hey my application shouldn't be longanything below an error message you know exactly where to go in this case righthere and Zach was changed to in this case error so that's step two RAM wehave five steps to implement log for net and step to his private biggest and mosttricky step of the mall step three is a comeback to a program that CSS file andwe had an assembly reference so under this task and tree in a bit of codeassembly cohen's base while Dad config XML configurator watch equals true so itcan be a bit confusing but basically this is doing it saying I have beenusing XML configurationto configure long for net and watch to watch it but the watchtowers make surethat if it changes their updates the logging appropriately so if we have tospecify the accident configurator that stands to reason that we could configurelog for now and different way and that's true you don't have to do all thisconfig you can configure long for net right insider code without a config fileand nothing demonstrate that today because it's a little outside of schoolboard doing it makes things a little confusing especially for new userinstead we're going as long as it was designed using XML configuration in theapt a config so this assembly statement needs in your application in one spotand one spot only this just says configure log for net to point that outto think we don't need to do this multiple times so if you're building inwinform application or WPF application typically what I would do is put thisline where you started your application so look for that static void mainsomewhere where that is I put this also named space in that same file again thisis copy and paste code it's not something you needed change they sendyour application unless an edge case that step three step four is we need tocreate inside of our class program we need to create a long reference and whatthis does is it creates a new instance of belonging system just go ahead andcreate private static readonly log for net dot I log writes that the type andnow we need to give it a name typically I call it long and I say equals longtrain at laws' manager that get longer now this is going to ask you for yourname of your longer this is where people get really confused I say get confusebut they may not actually even know that they're confused the way long for now asdesignedand you create a longer for each class that you're in you give it a name basedupon the class the area so this case I might get programmed ICS is my name thatpoints to this specific class that way later I can look it which program was Iin my longest message no point to programmed ICS something gets kids butthat they don't want to open more than one login since it doesn't create aproblem is thread-safe but if you really want to open one lawyer and since yourentire application not recommended but if you do what you can do is just giveit a generic name and then passed this instance around to all of your differentpieces here application so the most basic thing to do is to give it ageneric name based upon waiter at Chili's case programmed at CES now whenI change over to new class I have to give it the new classes name and if Ihad 11 programmed ICSA had one in the test folder then I need to make sure Iincluded the path based upon where it's atso say / program dot CIS and having the test for aids say / test / SES but thatmeans ourselves for each one of your classes there is no way of doing thisand that is to use reflection to figure out which class work in and give thatthe longer to do that we dosystem flexion method baseget current method .  declaring tape is long but what this does is it says usingreflection of me this now if you'd use reflection on or if you've read anythingabout reflection you probably have objection radar now is the same one thatI have a fresh start in that direction is reflection can be slow so I'm doingthis a lot more fun doing this in a resource intensive application thiscould be a serious problem because some application down significantly enoughthat it's a concern was a couple responses to thatfirst of all we're doing this once per class so not responding up classes at avery high rates and by the classes I mean classes actually use the logginglibrary unless you're speaking of his classes at a very high rate thatreflection is a very very very tiny part of our application in that case is notbe a big dealsecond it makes our application less likely to break in case of change forexample what if I aside happened on road after a footlong in Taiwan change denierprogrammed ICS to be my apt ICIS that would change the class name but itwouldn't change a static string rain here we're now this would pick up thatnew class name in long as such it may sound each case and really it is but itdoes make life simple in the fact that I can just copy and paste this exact lineinto every one of my classes that I need loving but there is a new feature indotnet four point six then meets the middle of both of these methods and showyou that in a little bit once we get the longing working so it's been a longworking and they will come back and see how we might go to tweak this to be alittle more efficient but yet still be a simple as possible ok so now with creditsave and now I've done step for step one was we had that new package step 2 waswe modified all the configuration step 3 we add assembly reference in step 4 iswe add this long property leases with one step to go to finish out and thatstep is to actually log something so down here and we're gonna say lawnfastest rate here so if you change the longer it be longer down here so longdied in his response if I what type of message logging so I can say long dadserror so here I am saying this message whatever it is this is my error messagethis message is an error I want right to my appender in this case the consolevendor so I missed a console right line hello world and then gonna log error toconsole that says this is my error message let's see how this worksrun I have hello world and I have this stream right here have my time I had thethread that I'm on I have the type of law to message this case an error andthen I have this is my terrorists such know that if we look down here this ismy error message that's the actual message gets written now and the restthis information is pulled from the system a South if you go back and lookat that conversion pattern we see that date with a thread the LogLevel themessage and then we didn't give it an exception information so that's how youuse long for a net to write to the console pretty simple but from here wecan move on to a more in-depth examplenataliehave locking working this one thing when I go back dress and that is the sectionright here where it's the reflection remember I said that we're looking atdifferent way of doing this and this is the one section that's to. net 4. 6% picok so if you're using the. net 4. 5 our previous then you're not able to usethis matter I use so if if that's the case continues the reflection or typeout your own name here but if you're done at four point six are beyond theheadlines create a new class called this log helper class and I'm going to createa new method called public standing long for net died I long it was going to turnget longer now here's the tricky partdotnet four points 6 has a attribute called caller file path now he usescontrolled and the using statement for system .  runtime .  compiler serviceshave been called caller file path and then we give itstring filename equals empty string in so what this does is it's an optionalparameter and if we don't add something to the filing then I don't fault the carfile path attribute takes over and gives us the path to the file is calling thismethod now has the full path so keep that in mind we are storing informationyour story a full path or file that also means that if you have two classes inone filesame file path for both of them but if he follows standard convention of havingone class per file then you'll be finein here we're going to return that .  Log Manager .  get longer then here for namein passing by on them and that's it every time I call this get longer methodwe're going to instantiate a new instance of the longer with this filename of the file name from where this method was called not harassment islocated so I see as inaction and come back over here and right now I'm stillusing the old reflection method of getting my name but let's see where thatwhat that does first base line before we make a changego ahead hit run as you can see we don't have any spot he was telling us wherethat long messages coming from we don't see a program that CSI we're here so wego ahead and change our vendor to make sure that we're displaying where thatinformation came from go ahead and close thischanger pender comeback tour after config and goes conversion pattern rightnow I'm saying then I want to date the threat it's on the level meaning errorinfo or debug and the actual message and passing it along with the new line theexception if there is one instead of seeing this thread let's go ahead andchange this to be the longer the longer is our long source aware that the law iscoming from Sophie runs program again we should see the console you I dot programcase namespace in the class name for which this log messages error was callednetwork capturing that information to display it let's go ahead and changethis to use our stack classes to show first that's coming this outan extra bonus a long healthier diets get longer and that gray simplifies thelog call makes it much easier to read and it makes it much easier copy andpaste without fear no the best does not allow us to stop the practice of coppingthis one's per class we still have once per class in order to get them longerneed to be changed based on where the law is called from let's go ahead andrun us again this time I see something a bit different in sidebar square braceswe have the full path to our program dot CIS file what this is doing is it sayingthis is where the file was when I was compiled so that's a bit different fromour namespace .  classname we had previous with the council you I dotprogram but this can be pretty helpful in a fact that is telling us which fileto look at when you are looking to debug so for those are you running dotnet fourpoints 6 or above that's an option instead of using reflectionnow we have longed for networking we're going back through and look at each ofour sanctions and expanded into a more full featured section so for examplewhat we're gonna do right now is look at those offenders in the apt I config westart with just one offender it was the console offender that's great fortesting and this may even be something you use and production to payingcircumstance but probably this is not the only appender you want to use everso in this section we're gonna expand out what other Penders there are and weare wrapped the section up by looking at the list on the Apache web sitedead covers all the different vendors that are available the first opponent isthe file appender name given his file appender again that's something youcan't blame yourself but for consistency sake I like to keep it similar to thesame as the name that long for tickets to the name is filed under and the typeis long for net dot tenderfiled under inside here first thing as he thanked called file with the value ofthe name of our log file story this on C Colin / logs / my log file that txt andthen I say append to file equals true we don't overwrite this one go ahead andenter the file is time and a lot he modeltype equals by gender file appender + minimal clothes that out what this tellsus is that we want to ensure that we can write this long file easily especiallyfrom multiple different locations without stepping on toes 30 had trentlott this as little as possible the file through my dad right now is our layouttype in this is very very similar to this right here in fact it's the same asup here unless you want change how the layout looks in this case we don't wantcopy and paste so now the way the log actually print out in the text file isthe same as it will print out the command line we could get into changesconversion pattern and a little further on this course we will talk aboutdifferent layouts and different ways to get information either system but forright now we're going to the same pattern since we're not worrying toomuch about the layout pattern yet we're just trying to figure out how thesedifferent vendors work the last 90 here is we could also add a filter in here tosay which type of long statements give written to the text file but we're notgonna do that here talk about filtersa little later so we're asking say that everything just launched as long as itpasses this check down here where the level set a debug member debugger andhigher just logged right now I really like that for a while now so we have nowcompleted our first new appender the file appender before his can see as anaction you come down his roots section and add this as appended to be used sotender dash RAF equalsfile under your spell it right and that should be it let's go ahead and test outthis new pender your head and resize this folder open over here to my logsfolder and for his starts opens up in my life how is created and we have amessage on screen and 24 to go way I wanted it yet because open up this textfiles compare looks very similar so I have the the time I have the location iscase the program that CIS type which is error and this is my error message sowill the same ones you sent a text file ones in a console now if I close thisout I start over again only have one long message here because it's a newconsole window open up my log file died txt I have two messages says when thebenefits of city to attacks by so that's the file appender now there's one flawthat you may notice with this and that is that this file will grow unlimitedbecause the long run this application to more than get handed us text file it'snever clean itself outwell this next appended a look at will help us with that was next up under thisrare call rolling file type is 14 pender rolling file appenderinside 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 besize so its gonna say that go in new file every time we hit this size maximumfile size value equals 10 cents to one source file get a ten megabytes we closeout star in the next century AD here is our max sizebackups in this valuable asset to be five so what this does is it says I wanta maximum of five of these up to 10 megabyte files so we have here it isonce our rolling file long dat txt hits the 10 major by Mark Wright one moreentry into it then a system is going to rename this file rolling file law gottxt .  one and create a new rolling file logged out txt once that wrong filelogged out txt it's the 10 megabyte mark it's going to rename rolling file longtime txt 2012 be rolling file logged out txt .  to its name the currently full 13rolling file long died txt doubt one is going to create a new ruling file onthat txt once it has buy extra files so we have our cars got one dot to dot 3Darfur and died 5 when the current ruling filed that txt which is always alazynation when that when his ten megabytes drop top 5 gonna kill the file and thenmade up for us $5 $3 for a list and then makes a new rolling file long that txtyour latest day is always in the file you named a rolling file long dead txtthe next newest data isn't adopt one and then always down till defy was theoldest daughter you have stored so this case around store ten megabytes in eachof those files or have five backup files so once we have a full backup set onceyou've exceeded our maximum storage capacity we could have anywhere between50 and 60 megabytes worth of data as it stands right nownext we're gonna say more I don't be static log file name is true in this ismake sure that the founding doesn't change now last thing I do is copy andpaste our layout is it the same and so that's one to get used to how painter'swork really is just copy and paste and then we just modify that things that aredifferent for specific offender in this case the file name is the same for boththe rolling file appender and a file appender they both have attainedco-founding any both have the idea of a pain to file versus over a new filethere are some variations based upon the type so little more specific the rollingfile appender that does the file appender but basically these offendersare about the same before you go on look at something a little bit differentlittle bit outside the norm for file defenders I wanna go ahead make sure wesee this action cases go ahead and safe three sizes again and one last thingbefore we forget we have to come down to the roots section and add this finalfender bender RAF RAF equals rolling byvendor should be good to gomore time we had run and nothing seems to happen this is the part of theepisode I did call find his mistake and go back and look at our config somethingis wrong he spied a year pursuing you may pick up really quickly for others itmay take longer but you look here remember I said he's a similar thisappender and this appender have a lot of similarities there lay out the same thefiles the same but look up here in such file value equals and down herefile name equals I was talking while typing and came out as name instead ofvalue was tries again run and now I have a ruling filed long dead txt called outand look at our file long it looks very very similar to our list just now thisone has one entry whereas this one has multiple alright so that is the rollingfile under very similar to the file appender I would recommend however thatif you're going too long to text file that you use the rolling file appenderyou don't get burned with a server that clogs up with a massive text file evenhere fairly certain he'll come back to that file and get rid of it everyone soI'll make sure it stays small you really don't wanna help file they can growwithout end so I get rolling file tender and always just keep it delete old filesthat way if you don't get to something or if you get an error in a loop andjust keep spinning up issue after issue long in the log file you don't shut downyour computer or server this next appender can get a bit tedious to typeout your head and copy and paste a walk you through each thing does start outwith the appender name equals ATO net offender and a type thatunder 8000 under all rights in here based in my code and that's a lot ofcourse let's go back and look at what does the very first thing while Jack isthe buffer size the ATO dotnet gender rights to any radio data source in thiscase writing the sequel server so this right here is one of those guaranteedthing that will trip if you copy and paste someone else's config I have seena number of questions from people either on Stack Overflow our code product orelsewhere were saying my ATO dotnet appender does not work I've tried it Itried the text layout and it works I tried to rolling tax it works and I cometo ATO and nothing works always comes back to are almost always comes back tothis buffer size so what this buffer size is it a sad instead of writing aquery to sequel server every time we have a long message to wait until I billa buffer so in this case after 10 log messages have been written on your rightall ten of those two single server and that just keeps the traffic down asingle server the kicker here is by defaultwhenever you see a demonstration on line or even at the long for an essay that ifit will be hundreds you have to write a hundred log messages before any of themshow up in your single server now when you do close out your application thoughsupposedly written to single server so if you're watching us applications openyou may I see anything we close it you may see those ten twenty thirty longmessages written a single server at that timemy recommendation for demo purposes is that you set this to one that way everytime I log message gets ripped the server you see it in highlighting timesit may put extra strain your single server but nothing that it's not able tohandle the production values in private much higher than this but we're reallydepends on your scenario for instance if you rely on up to the minute reportingon your errors in the logs then erosion have this is lowest possible maybe evenone because if a system does not write a long message very often and you have a608 maybe hours or even days before that buckets filled up waiting days to findout the you have an issue is not ideal for demonstration of keepers at onethe next thing is our connection type in this says hey we're use a sequel serverconnection and feel free copy and paste this this is a whole bunch of stuff thatno-one memorizes next we had a connection string and this just sayshelicopter database in this case and cut into the local database or dot thecatalog amusing is my my database itself that's application to be and then usingthe integrated security which means it going to use my login as the securityfrom a single servernext is the command text this is the actual query to run in this case let'sget down to hear the command typist text that means I'm running a raw sequels toin this case an INSERT statement so i'm saying insert into the table logs here'sthe columns to use and then here's the values to put in them now there is analternate that's much easier to do in this file is also in my opinion betterpractice and that is to use a stored procedure so instead these two lines areliving here for now to show you a difference but you would play itscommand text value would be the store procedure name and that's it and and thecommand type the value equals stored procedure so you wouldn't put both ofthese in here this one and this one you choose one so either had a like thatwhere you had it like thatpersonally I like this method better because it's so concise out to type allthis out I can also do things are stored procedures such as having extrastatements around my insert or making an upsurge statement so that if it'salready a statement there that matches this which shouldn't be but if there iswe could do an update 7 answer there's a number of things we can do in storeprocedure but size just the actual insert but I use it is up to you sochoose used or procedure or the actual command text go ahead and take this outboth work the same way so I can you demonstrate both big deal both workagainst you for your call I'm gonna show you one more thing and that is theparameters right here these match up to these parameters down here now in astored procedure takes parameters and their named just like this but we don'tyou specify them because they are specified for us but for the INSERTstatement whereas just taxed I have to specify the parameters so that is onething I know is that we have to actually specify the parameters passed in inweird again passed in alright let's back out so we have a number of parametersdown here let's go through them when they won the first parameter is the atlog underscore dates between specific parameter name that D be type in thiscase it's a datetime tape now this is a C sharp type not a sequel type so nothis DateTime not daytime too was when I actually story in in the databasenext is the layout this looks very familiar if you're looking up here wasthere is needed this only instead during the pattern layout I am doing the wrongtime stamp lay out the timestamp for his log entry and so instead of specifyingthe conversion pattern here it just knows ok you're at the time stamp ongive it to you that is a bit of a deviation from what we're doing up herewe could do that we could take us out instead put a layout that uses thepercent date absolute but that's a lot of the DVD a little bit and show how itlooked a little bit differentour next parameter is the at log underscore thread and this is a type insee strength now in CString identifies bar chart if you're familiar with sequelis to type of string feels akin story there are two major types the first typeis March are annexed is nvarchar bar chart is a variable-length strengthwhereas in March are is still available thanks drink but it can store Unicodecharacters in this case I said I don't think I need to store Unicode charactersin my database therefore I'm they use large garfield's and so we have topassing and C string as the type if we were storing nvarchar are considered anCString we would just do strength so that's the differencethe size is the size in our database in this case of 50 characters and then thisshould be layout pattern just like up here to lay out pattern can be verycomplex plots this is the layout pattern for one field I'm storing each field ina separate column therefore it's very very simple here I'm just story butthread to come down here to the next item we have log level it's an ancestryas well against it the characters in this just stores the level and that'sour debug error warned fatal or involve the next one log source that's thelocation with a longer in it and so I made that 300 characters long and thepattern is just that percent longer next we have actual message this is what wesend when we call log and still industry and its four thousand characters verylarge but you make sure that benefit you could do in March our Macs which is muchlarger if you want you but in this case I say you know what 4000 characters isplanning to that's about shoes and find out here we have the exception againstring again 4000 characters and the layout type instead of being one ofthese items i'm saying give me the exception layout so these are the fieldsand inserting into my store procedure note that we don't have to put just 11a. m.  into anyone field and we don't have to use it just onceso you could get creative in here where maybe you rate each item to its owncolumn but then the end have a column that is the printed lawyer what youwould see a tax policy like backwards the combined file what you write thedatabase is totally up to you used to make sure that your INSERT statement oryour store procedure will take that information and so speaking of storedprocedures let's go ahead and look at our store procedurefirst here's my table this is the logs table its me application TV and I have ID along date with red the level the source the message and the exception soI did know the varchar sizes match up with what we have in our web config filenext I create a stored procedure that takes those same names and inserts themand there's an INSERT statement does nothing different than what weoriginally had with the INSERT statement for the command text but now I have itwrapped in a stored procedure finally if you come over here to this window I hada slow start from logs if I run this I see that have no entries so far let's goahead and change that will come back over here we come down here to our rootssection and add this appenderand that's double check that insurance rate ADR net under so we should be goodlet's run us I have message on the screen but come back over here tosequencer I R us again I now have one entry date there's a date and timethere's a thread number there's the log level there's a source it came from andthere's the message and we don't have exception so in just a few moments wewere able to use this pattern to write a sequel database now we're starting toget into things that can be more useful in a production environments now we haveto arrange a single server let's look at other options for radar data if we goback to the long for next site logging .  patchy dot org / long for now we comedown here the SDK reference there's this long for netappender and you know every time we have created pender it's always been lost fornet pender .  something so go ahead and open that up and as a whole list ofthings in here and we look down here we have these file appender class and itwill tell you all about the file appender it's not great but it issomething and you some clues as well do it also gives you an idea that you cando a file appender which we already knew but there are other painters and hereyou might not have known about for example the ANSI color terminal appenderI've never used that there's also the buffering appender skeleton buffering 14pender may not useful for you and your case but there's others in here thatmight be for example there's the eventlog appender this rights to thewindows event log it's something that sounds great but I would recommendagainst trying to use in too many situations there are situations whereit's rightbut the most part it's not great in the reason I say that because you have tohave special permissions for the use of its running this application so if thisis a web application typically you're running under the asp. net account if youare under that accountyou either have to change the permissions that account which I don'trecommend in order to get more rights or you have to write to the event log onceusing in mister account in order then kind of allow that to be written fromthen on using the asp. net account its little clunky but it does have itspurposesanother one it has its purposes that maybe a little clunky for you but it maybe perfect or somebody else is the SMTP appender this will allow you to sendemails out whenever you have a long feiler in my advice here is to make surethe only sending emails out when you absolutely need todon't send emails out saying yes I got this piece of code especially if it's alittle especially if you're saying that your boss this is just one more wave ityou can do something with technology that you probably shouldn't so I wouldencourage you to look through here look very different vendors find ones thatmaybe you want to use or that fit your certain scenario where you think theymight and then go find examples of how to use them and there are examples inhere if you come down to configure examples we can scroll down find there'sthe MS Eagle server example isn't access example both he's an ATO net appender inthis case the access one versus the generic one for the single server isOracle Oracle as a whole bunch more in here and you can go through and not onlysee ASP net race offender but also how to use it if we come back up to a singleserver one you'll note that the buffer size is set to a hundred so as make surethat you take whatever information you get in here with a grain of saltit may be a valid setting but may not be the same that's rightfor you in so that wraps up our section on tenders we've gone through identifiedeach of the major types of tenders and also where to find out more informationabout other alleged case of vendors Nextel look at filters if we come downhere to the bottom we have this one filter it says only give me items fromdeep above but they're more houses we can add to our panders to limit whatinformation they get so let's get to that nowbefore you get in a setting up our filters I want to a little bit ofhousecleaning first let's go ahead and collapse over a Penders Leebetter-looking file here only the console appender open and we're justgoing to use the console for now let's go ahead and commentout these other three offenders from me used no I'm just commenting them outfrom the roots action I don't need to actually change the offenders themselvesif an appender isn't mentioned in as root section then it won't be called fornow and just the console offender here I have just the console penned up herelet's come back to the program dot CIS and let's make a few changes here inorder to have more log statements person to leave the ones we have and then startcreating new ones say long does debug that's the lowest level message so farthis whereas a developer colon tutorial was right next let's do lawn dads infois the next level up it will say maintenance water turned on next lawthat onesays 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 atry and make this divide by 0 exception and here if we throw a divide by zeroand do a long dayerror is happier can be involved want to debug if you want it just makes senselogically usually if you're throwing an error and error thrown you that you callan area long statements again it's up to you if you want say it's only for debugor this error message isn't a bad one that's fine in his case was calling Drmessageand then here actually include the exception to this is one of those thingsthat I told you about but you haven't seen yet and that's the idea of him passexceptional long as wellback over here after I can we have this new line and then the exception and sofar has been black but now we're actually use it so that's a receptionlet's go ahead and create the exception by saying they are X equals 10/10 sinceI 0exception last and highest only long scale is along that fatal explode ok Ihave five log messages in increasing order of severity so from the blog thelowest involved in Warren an error then they'll first let's make sure they allrun alright I have a bit of a mess here in the reason why is because I'm loggingout this very very long path to a program that CIS so what's changed thatlets get back the reflection method was once again and now it's a lot betterit's a little shorter in fact you can trust message down even more so let's goahead and go back to our apt a conviction say you know what we're gonnaI just as conversion pattern to only give us the level and the message wherethe interconversion patterns more in the lab pattern in a little bit before nowwe can just tremendous message make a little simpler again and now we have alittle better system we have debug info warning error and then underneath theair we actually have the exception and has fail so since you haven't seenaccession before let's look at it we have the airline says developer we tryto divide by zero again we have a new line and now we have exception messageexception is system .  divide by 0 session attempted to divide by zero andthen just leave whereas at 125 in the program to ICS so I can be really greatdebugging information for when you have an issue since we just want the actualinformation on the screen now let's go ahead and take out the exception we knowcan do it we don't have to do it again and now we have a very clean screen thathas just five things on it and in the order from debug their fatal that's agreat setup for teaching us how to filter out different items there's anumber of different ways we can filter defender we're gonna touch on the mostpopular the most used and then there are some extra ones we can go look at lateron the documentation so let's start by creating section called filter the firstbuilt around do is the level range filter so type equals one for her thatlevel range filter and this has 2 entries in itfirst we have the a-level how is blank for now and then we have the max nowleave it blank as well for now so little man and a level max are be bracketsaround which you want to capture your blog entriesremember that debug is the lowest in fatal is the highest so if we only wantto capture Warren and error messages the low the men will be warned and then maxwill be error what this says is has released a warning level and it can beany higher than error message which means that we're not going to capturethe debugger info and we're not going to capture the fatal what's runs and seehow it worksmerry go we have worn and we have error but that's it the rest of them don't getalong just console instance right now the console is the only appended it'sactually logging they didn't get along that are at first that may sound badthing you're longing messages that don't get captured anywhere but think that onethrough four minute if you put a bunch of statements in your code that are longdone debug and it only for debugging your application you don't want thosedebug messages story where most likely unless you have a problem then youcoming in here just your filter to say yes give me debug messages so we canjustice again if you want if you wanna include up through fail because changethe max the fatal and now we have three statements war on terror in fatalso that's the level range filter this is one of the few filters that if it doesnot fall within its boundaries the log message does not get written imma goahead and comment this out and create new filter that way you can see how eachfilter works in my code to create a new one in this one is going to be filtertype equals 14 net dot filtered through a string match filter so that's good Ido it in a match the string pattern inside of our log message so string tomatch value equals and let's say has maintenance to now only maintenancemessages with a lot right we'll find out and we had a lot more than just minutesmessages if we look through as managers we see no reference to maintenance inthe error or the debug message and yet all five are showing upwhy is that well remember with the range I said this is one the only ones that ifthe message falls outside of that range it does not log in this case it matchedmaintenance on three of those entries before the other to it didn't match andit fell through to the next filter since there are no more filters it assumed wewant to log it seems counterintuitive because it feels like we want to notinclude something if it didn't mattershelter but the reason we do this is because you can have more than one cellfilters inside of an appender but if you want just matchon this filter you have to create one more filter at the end of type filterthat mean I thought there was nothing inside this is the if you get here youare done don't log so now it's going to match the maintenance training and itdoesn't find it is good I dropped out of the next filter the next order saysdon't log was stress again ok now we only have three statements and all threeare making statements you should also tell you something important about thefilters order is important it matches against the first filter if it doesn'tmatch it will typically drop down to the next filter the exception being thelevel range doctor if it doesn't match here it's done so that means if I movethis filter the denial felt there above the string matched filteriraq again nothing that's because the first built in a match was this deny allfilter so it's moving back down to the bottom the next filter we want to goahead and comment this one nownext filter that I'm law internet filter .  level match filter this is verysimilar to the level range filter except its matching on a level surface level tomatch value equals error this is only going to grab the error level but itdoes fall through just to stream matched filter which means that we have tocontinue to have this than I are at the bottom but see it in actionall right there is just the error message let's get a little more trickyand create another level match dr.  copy and paste this and say I only want debugmessages so now I have all the care and debug remember these fall through soit's not an errorfalls down the next one it says are you debug its runs again and now I have twostatements the debug statement and the areas that there might be times when youwanna captured two of the five and they aren't right next to each other so alldebug messages but also failed messages as well so as you can see their maindifferent ways we can configure our filters to pull out exactly what we wantfrom any situation next week I'll look at the lawn patterns the informationactually write out to the database would tax file the screen will look at thedifferent pieces of information we can pull from a system in a drawbacksassociated with gathering back informationnow let's dive in that logging pattern the strength gets printed out a screenor get store the text file right now we have just the level and the message andthen new Lion exception in our conversion pattern or that loggingpattern let's go ahead and clean up a couple things here first before we makesome modifications to this first go ahead and commentout all these battles go ahead and move them we don't need any more so sincehave removed all my filters everything will get printed out now know we stillhave this down here that says debugging higher if I change this to error it onlyprint out error and hired even though I don't have built up here justdemonstrate right now I run this I have all five messages my debug info warnerror and fail but if I change this to say error iraq can only see the air andfatal message for our purposes let's go ahead and change it one level highercause a fatal now only capturing one message just that fatal message sayingthe water pump exploit that's good enough for testing purposes because whatwe're going to concentrate on is this conversion pattern now you've alreadyseen the standard pattern so for example the date the longer the level themessage the new line and the exception is a pretty standard and trees as a fewmore standard ones for example we had at one point the thread but it's a fewextras we can add I'm gonna use the new line after each entry so we know whatwe're looking at first legal level here with us a leveland then put new light at the end of next year as a message that we're attake out exception that gets a start we run that we now see levels fatal andmessage is maintenance water pump explode now we do have an extra spacethere was take that out again we should see one per linelaid out nice so it's a few extra things one line per time so we know we'relooking at the next one is the UTC did put UTC date and we'll do that well thisis just like the date only as in if the Utdcompare this was put a new line and then put the date certain dateand make their absolute well okay so we have the UTC day and the record date asgo ahead run us now for comparison we have the level message would berecovered the UTC date is 05 3943 the date is 01 3943 so I'm four hours off ofUTC time next let's add the timestamp this was a bit confusing for people notquite sure what what information is giving them in this case 149 its riseagain announced so what is thatwell I am put the new line of go ahead and put them in their first before youstart talking about it and that's 110 so what is that times there were times themis the number of milliseconds since the application started their situationsthat can be very useful now is when we get into the deeper waters the thingsthat aren't as straightforward or aren't as efficient these things so far fairlyefficient when it comes to rain to the lawnew line and we're going to add two new pieces of information first one is theidentityin a square poll from the principal denied any dat mean property and thesecond one is the user name that user name polls from the winner's identityproperty so these to rate here can be a bit slow and they can also sometimesgive you non information or be emptylet's go ahead and run this second CD identify mind is blank and yet the username is office tower / team was that's my login name sort of paying environmentthis may be great information or it may be non information so just be aware thatmight not always show up the way you're expecting it to this is doubly truewe're talking about a web server remember that this application runstypically on the ASP net account in that case username will probably be ASP netusername not the name of the user login next there are few entries they canpinpoint where in the code we had the problem first let's look at the locationand this is the location the code where there's a problem now in order for thesystem know this you have to have the debug information it works a lot betterand debugging that was in the production environment just the line number samething here as far as working better and debug and doesn't production and finallywe want to pull the method name again seems cleaner so in this case since I'mrunning in debug mode in Visual Studio it knows them running from programmedICS it knows on line 32 and the method is the main method these last three canbe very very useful when you're debugging just be very clear that thisis going to work great in debug on your machine going into production you mayfind non day here you may find it empty may find information it doesn't quitemake sense because it doesn't have the reference to pull from the rightlocations so that's a brief overview of the more advanced I am so you can logbeside the on the RT covered but we're not quite done yet we also have theoption to pad or shrink down our informationremember we're adding information to database we said that a log messageshouldn't be more than 4000 characters or that exception information shouldn'tbe more than 4000 characterswhat would happen if we had more than 4000 characters that be a problem tryingto put that into the databasewell long for now has an option for that if we come back here lets choose themessage itself unless it a message should only be five characters longnow that's obviously not a real-world scenario but that will give us anobvious to the matter we say topped 5 that dot 5 indicates that the message atmostg5 characters if it's more than that it's gonna start trimming off from theleft as an action so my message is LOD ok that's the part of the word forexploded the reason is hello dee dee and notmhm TV was at the beginning of the message that's because we capture theend of the message everything else is trimmed off so if you go over your fivecharacter limit in this case the first part of message kids to lead that isn'tsomething you can change a setting that's one of those things that could bedone all better in long for now I would like it where you would add the firstpart of the message and then trim at the end but that's a nigga do in code oreven make a interface for your log message that goes ahead and trims offthe end of it it's definitely doable is just not something that's built in to bedone with 14 that ok there's a couple more options we can do here we can putnumbers before this died in this would be the minimum number of characters soif I puts in here a minimum of 20 characters and a maximum of fivecharacters what is going to do is is going to trim off anything 15 charactersbut if it's less than five characters say it's one character it's going to adda space in that space is going to go and the left hand side of your message so ifI had just an each in a sealed its gonna be space age because I have that toothere if I had yellow exclamation point because it's six characters it was sayhelloE L L O exclamation point so those two can work in conjunction with the spacingif I instead put a negative sign from it that's going to put the spacing at theend so again might just in each in that message it would be each space insidethe space age so if you doing a space to limittext file you could make sure that your minimums and maximums of the same andthen anything less get spaces anything moregets cut off and that's all there really is to logging information out to ourfile a layout that we like that's the conversion pattern now have a handle onall the information that long for net provides forest and hits log messageslet's take a look at how we can bring in our own information when we talk withthe advanced features of luck for nowsometimes we are logging inlog for net you just want a little bit of extra information you could bring inthe message but maybe why and different field or maybe using that ATO dotnetappender where you want put in different column if that's the case there is a wayto bring information in let's start by cleaning up our conversion pattern herelet's just do the message itself looks ok we just have maintenance water pumpexploded that's fine for now let's go over to our program and we have thesefive messages only this one is being pulled because it's a fatal message andthat's the only ones that we're pulling in using this long level so let's createa loop down here in here and do a for loop yes a 12 lasted five which meanszero one two three and four so it's five till now just and we're going to saylong .  fatal this is message number and the eye of the end and actually we'regonna change that from something different because we're already using Iup here or just take away the declaration has already is okay so wehave I 0 ice less than five as long as five messages we can go ahead andcommenters out so now we have five failed messages that say this is messagenumber zero one two three and four runs and find out okay so you have this ismessage number zero one two three and fourwell maybe we don't want to have that in the message itself maybe I say somethinga little more generic like this is as a fatal error in the process and may wantcapture that that I information somewhere elsethe way it do this is to use the properties of water for now we come hereand say long for that God global context and there are multiple contactsthere's the global contacts in this thread contacts and go through a listhere and see all the different contexts a logical thread context these are allscopes so the tighter the scope the more likely it is to be captured so forexample if I have something a property name in both the global scope and in thelogical thread scope then the logical thread scopes variable is over rightwhat's the global scope that can get really complicated don't worry about itif you don't know which scooped you want use a global scope that will work acrossthe entire application the smaller ones are for specific threads typical so asto youglobal context .  properties and now you can specify or own propertylet's call this property the counter property and we're say this equals thecurrent diet I know we can put any kind of strange information into thisproperty which also put other types of David in here and we'll get to that in aminute before right now we're going to store I and that's it we don't actuallychange our log message because we have now created new variable we can pull inin this conversion patternso let's go ahead and pull out in so instead of having it in a message I'mgoing to say the numberdash the message so let's start with our percent sign and then we save propertyand they get the name in our cases countercreators so we have percent property curly braces the name of your propertybut when you called it and I'll put my dash here and that's run this so now Ihave zero one two three and four within the dash and then the message is a bigdifference because I could have put that in the message itself but the differenceis I now have this as a separate property I can pull in different way soI have made a deal yet tender I can put that in different field now we're donehere is just past the value of and I dot toString got the information is storedas text but there is a way to have I don't panicproperty so let's set that up and over here and create a new class and I callthis class the counter class publicand one profits into property call this counter so it is going to store theinformation that loop so I 01234 will store all in this number here and lastnight to a public override string toString and returning the base thatstrength I mean to say that I want the loop counter to strength so whenever youcall this class and say .  to string a class instance instead of returning theclass name which is standard for a class instance it's going to return the stringvalue of the loop counter into variable so can save that come back over here tooare programmed at CESdeclare and new variable called counter recall this hour I asked OJ since wehaven't I J equals new counter next move out this global context out of my loopand pasted up here when I was in my lube it reassigned as property every townwent through now and when I say it once so instead of assigning it a variablewas just in a science jay jay is the instance of my counter class nowwhenever J changes the two string value is remember two strains actually justthat loop counter wherever it changes its going to change the property andlong for now shut down here I make things a little messy don't do is inproductionJade outlook count equals zero and then Jade Luke hour or less than five andthen Jadecare plus plus sorry place that I variable with the propertycounter using my instance call Jay that's all I've done I've moved thisoutside of my lips are only get a signed once its rise again and there you go itlooks like nothing has changed except in only a sign that property once it pickedup the changes using that toString method so great right as it is this isdefinitely a test just show up where can do but what this demonstrates is thatyou could create some sort of property or some sort of class instance theycaptured information or send information to log for net based upon certaincircumstances in your application dan you justice it once in that globalcontext and in your configuration you can pull that property over and over andover again and will always get the latest information a little moreadvanced it's not something you use an every application but where you want itit can be a great help so they are a couple ways you can get the most out ofyour long for net using some advanced logging techniques now let's review whatwe've learned and see where we go from hereso that's the basics and the more advanced topics of long-term debt reallyonce you break it down it's quite simple we started off with those five steps toget long for networks first adding our reference using nougat too long for netapplication next we went into our program dot CSN add this entry righthere which is once per application then we add this team right here whichhappens once per class or once per time you want to instantiate you don't haveto once per class if you don't want to end then we moved on to creating thisconfig section so we created this section regular says hey I'm along fornext section and then in that long brunette section we add our vendors somewith filters some with different conversion patterns then we came downhere and add our roots section which points out which offenders are workingand then with the overall filtering level is finally we create these longstatements that log information to log for net as long as it accepts them towrap up we create some advanced data too long to our long for instance we createdynamic property using our class instance allow us to our can fix it pullthe informationdynamically based upon the point in time it which was called so that's long fornet very very simple at the end of day you just want to create these longstatements you pepper these throughout your application where you need them atthe level you need them since he know how to filter and how to limit whichlong statements get logged to your lawyer appender source will it be thetext file database or even a console window you can mix and match and playwith these things for example you may have a console windowyou don't care for scrolls like crazy and see send all her did to it where youhave your single database the protect a little more and he only rate warningsabove and find that text file which might be a backup for your single serverbut you only want to write the exception data errors and the fatal injuries hemay say you know what i mean a rolling file because it's just a backup and Iwant to only keep a hundred megabytes words of miles across 10 files based onwhat we've learned this course that's definitely possible it's possible usingthe example we've already done just to recap this video is a companion piece ofthe article I wrote on the log for net tutorial so all the information we'vegone over here in this video can be found in some format in this article soif you want the written copy of it go ahead and go here if you want moreinformation from a source you can go to the apache log for net site and get theSDK reference or the how to's or even conceive examples for dependency youwant that's really all there is for long for now I encourage you to play aroundtry things outbuild a dental out and then once you have your config file the way you wantto go ahead and convert any production use these things whatever you want tocapture information inside your running application down the description youwill see links to always different sites you will also see a link to the gift ofa positive re where all of the code I went through in this course is start ifyou look you'll see that the code has been tagged at various levels for eachof the different sections in this video you can download code back to where itwas at that specific section also if you like this video if you want to find outmore information on other providing both here on YouTube in other places as wellgo ahead and sign up for my newsletter I don't spend a lot of emails out the waydo I tell you about the new and upcoming courses than creating and I also ask foryour feedback I love hearing from you what you're looking for your feedbackshapes these courses so please let me know what you'd like to see next thanksenjoy using log for net without being afraid that config file

Source : Timothy Corey

0 comments:

Post a Comment

 
Toggle Footer