application logging is a bigdeal. keeping track of issues in software in production needs a priority of anyapplication developer analyzing what went wrong monitoring the applicationresponsiveness and getting metrics about usage are all important to deliver ahealthy sustainable app if you search the web for application logging in c-sharp it bringsup a number of options and suggestions if you come down here to the.net loggingtools and library, it will give us a list of a number of different loggers. so wheredo you start
well they come back over here to thestack overflow questions and answers you'll note that a lot of these in theanswers 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 youlike me at this point you figure that now is a good time to try out log4net tosee how easy it is to wire up and use in a project and that's where he hit the wallthere 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 goodinformation here it has documentation but rather ugly and confusing that's whyfive years ago i wrote an article on
log4net for code project afterspending days digging through the documentation experimenting in test appsin figuring out the answers to my questions i decided to make life easier for myself andfor 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 ofthousands of readers and continues to generate about 4,000 views each weekthat tells me a couple things first it tells me that log4net isstill a popular logging library and second it tells me that people are stillconfused on how to implement this
library that's where this video comes ini learned best by being shown how do something i figure there are others of you outthere just like me so i'm create a video as a companion piece to my code projectarticle i'm going to walk you through setting up log4net for the firsttime your application you can follow along as they build the application inand then add logging to it. we will start out simple but then we will dive in thedepths of what a real-world implementation might look like by the end you should feel comfortableadding log4net into your application lets get started
to get started on let's start with aconsole application this is going to start off with a basic hello world stylelogging demonstration where do just enough to get logging working the coolthing here though is once we get long working we can actually scale this appout into something that would look like a production have very easily so i startsmall and build from there so here i sit up a console application i mean thatlong for net total as a solution and the product name is console you i okay let'sgo ahead and create this application so here's my basic console application ifyou're not familiar with console application it looks a lot like the daswindows of all and if we're at right now
is going to pop up a dialog window isgoing to go away let's instead go ahead and add a couple commands just to havesomething on the screen first we're going to create the consoleright line and say hello world and next we're going to say console rely in orderto stop the console going away this way the the console and pops up is going tosay hello world but i'm gonna pause until hit the enter key let's go aheadand run this year ago there's a hello world application really simple rightnow just as hello world it waits for us to give us some kind ofinput we hit the enter key and it goes away the applications done so now addinglonging to this is going to take five
steps the first step is to go to ourreferences and same ang nuget packages in here let's search for log for net person that comes up is the official fornet new get package heidi is log for net go ahead andinstall that that's it for step one we go back to references and expand thiswill see the long for net dll is being brought in step two is a step thatreally trip people up ok so don't panic we ever step can lookoverwhelming but once we break it down you'll see it's not that complicated forstep two is to go into our appetite config file this right here now ifyou're using a web application this was
a web config file for our purposes isthe same difference if you're a desktop application it's apt icann fee if you'rein a web applications web.com be the first thing they do in this section iscreate a section dedicated to log for net surfers can fix actions inside here section blog finance and that made meanything you want but i recommend keeping a log for that type equals blogfor net config log for figuration section mendler commalog in at right nor does all that we just need to close it out ok so we'redone here is i said im gonna create a section in my config file called longfor net look for that alright so now
let's create a section called log for now everything in here is gonnapertained to creating a log files wendell log files what information alongto how long the great thing about putting information in here is that atruntime we can change the configuration of our logging without having torecompile our application the first thing to add to our long-term debtsection is what's called an appender now i pender is basically a logging toolit's what do you want to log to in essence ins we're going to a log rightto the console window since we already have a console application it's thequickest way to make sure your feedback
and eliminates a lot of problems of dowe have permission to file system to have to mention that database is aproblem with the connection string all those things go away because it's a veryvery simple longer or pender so first we give a name again asking me if you wantbut scott console appended next the type and this is the civic so long for netdot appender console bender we're going to look atmore penders in a bit before right now we're just going to use the consolepender gonna walk you through how do it lateron she had a good documentation and find all different vendors and how to useeach 129 define the appender line now
you put things inside a pander to theconsole appender we tell the console how great our message and that's called thelayout type equals the long for net dot layout had information that i can put theconsole but what he want on the console lay down there's more than just theactual message while log for example there might be exception data or thedate and time or the long level inside a layout for the consulate hunter we havea conversion better value has to be that pattern you are right out long for now has a specific way ofgetting a what each item is and we go
over all the values could be gonna giveyou a pretty standard layout first date and they're a specified that should beabsolute there are a couple things in know about the state first this is the local dayton time ifyou want the utc date he doesn't specify utc date before the important if you'rerunning long for net on a web application that may be installed onservers in different time zones the second thing to note is thatabsolute the absolute is a pattern it just tells us dad this is a specific wayi'm gonna lay out the date and time you could put your own pattern here but somuch slower process for log for net to
figure out how layout date compared tousing one of their three built-in patterns for dayton time in this casethe absolute pattern next let's put the thread and this was just give us thesethread number for a currently running thread next let's do the level of theerror that could mean doesn't information log or it could mean theerror log off a dialogue ranging between finally let's put themessage this is the actual message you give the logger and then just in case wehave an exceptional augurs well for example say we threw exception want itwe want to give it a message we also want to capture that exceptioninformation as well we can pass both of
those pieces of data together to thelogger and in this case right here if we can add something for the exception tobe displayed nothing to show up so go ahead and create a new line first andthen next up with the exception and no there's no spaces there the percent signin a case of start of a new tank in so i'm saying read the end of the messagefor new line and then right away with the exception if there is one otherwiseblank and that's it for now is closed our tank and now we have and pendercalled the console offender but has a layout that specifies the day the threatnumber of the threat of where the law was culled from the level of the messagethe actual message is being launched and
then if we have one we're going to putthe exception as well all of this information will be written to ourconsole every time you log a message so that's an appender pender again is justsomething we're alright the log to in this case to the console you can havemore than one up yonder in your long system you can even specify that oneappender get certain type of log messages or certain messages based uponcriteria give it will get more of the depth and detail those things a littlebit before now again we're just going for the very simple tutorial just to getyou started then add on to it so we have one of pender but we're not done yetanother log for next section the file
piecemeal had just called route and in here we need to tell long for netwhat up hinders to use and then we also can specify the overall level of loggingto do so i start with our level of life so level value equals yesterday but whatthey're saying is that a lot of every message that the debug or higher now there are a total of seven differentstates for the logging levels of wage which only actually right to five ofthem the other two are just for our convictions so here i am specifying thedebug level that is the the lowest level mean we're betting a log all of ourmessages where say if it's a debug log
if it's info get it was worn logging was an error logget it was fatal to head lying if i said instead debug i said error then iwouldn't long the debug message the infamous age or the warning messages iwould only long error and fatal messages so this one setting we can change howour system is working as a production at typically we only while log errormessages we need to know the applications crashing or throwing errorsthat we're not expecting but say we have a machine that's throwing errorsconsistently with you come on it and machine and wants to running change thislog level from air all the way down in
debug than all those extra messages thataren't being logged normally will get picked up and put door locks this liquorlaws much larger but that's what you want we are trying to track down problemonce you're done drinking problem he can go ahead and change log level back toerror so this right here is our first look at a filter and we're getting twofilters in more detail especially looking at a penders and the idea ofhaving a pender also have a filter level but for now let's go ahead and changesback to debug one thing i know is i've given youfive logging levels have mentioned five debug info war on terror and fail but isaid there were a total of seven the
other two are all and off so i wannaturn logging off entirely i go ahead and change this to off now nothing is lockedor if i want everything i can also say all in debug are very very similar inthe fact that both of them along all messages so for right now we have ouroverall filled their a-level we've sent to debug which would give us all themessages from debug on up or basically all messages the other thing we do is specify thatwere using the console appender the reason we have a dealer's is because wecan have extra vendors and our config they were not currently using so let'sgo ahead and specify the console
pedigree just create do this by saying ipender dashrath and then press space and ref equals console appender becauseattack principle that they now here is this console appender gets itsinformation from this name right here remember i said that you can name asathey want but if you do decide to change this name you have to change thisas well calling yet console pender makes it veryeasy to understand that this appender is the console pender with a hard to lookback to the offender and then looking the type alright so go ahead and saveyour apt a config file if you look at now and you first walk in with all thisalready done it can look a bit
intimidating but just remember this justspecifies the red have a long for next section in our config file and go aheadand call that this just specifies that we're going to write to an appender orisource to capture our log information inside here we have a conversion patternthis just says here's what the log message should look like and finally wespecify by that we need to call that consoletender and that the overall filter level for our messages is debug the configsaction isn't something that i typically reach he from scratch every time i copyand paste quail bit my previous configs or from my blog for net article rememberi said that i wrote that for myself as
well as for others i use as my ownreference guide because they're fine either go to then keeping notessomewhere else copying and pasting config isn't a badthing is just important to you know why things are doing what they're doingthat's why those pitfalls i see a lot of people do when they first start usinglog for net dialer config sections say oh my goodness that's so confusing soimma go ahead and copy a working config section from someone else and then pasteit in my code cross my fingers and hope it works that's not the wisest choice so that'swhy waukee third detail step-by-step of
each piece this configuration i doexpect you to type this over and over yourself but you really shouldunderstand what each piece does and why it does it that way when you decide heymy application shouldn't be long anything below an error message you knowexactly where to go in this case right here and zach was changed to in thiscase error so that's step two ram we have five steps to implement log for netand step to his private biggest and most tricky step of the mall step three is acomeback to a program that css file and we had an assembly reference so underthis task and tree in a bit of code assembly cohen's base while dad configxml configurator watch equals true so it
can be a bit confusing but basicallythis is doing it saying i have been using xml configuration to configure long for net and watch towatch it but the watchtowers make sure that if it changes their updates thelogging appropriately so if we have to specify the accident configurator thatstands to reason that we could configure log for now and different way and that'strue you don't have to do all this config you can configure long for netright insider code without a config file and nothing demonstrate that todaybecause it's a little outside of school board doing it makes things a littleconfusing especially for new user
instead we're going as long as it wasdesigned using xml configuration in the apt a config so this assembly statementneeds in your application in one spot and one spot only this just saysconfigure log for net to point that out to think we don't need to do thismultiple times so if you're building in winform application or wpf applicationtypically what i would do is put this line where you started your applicationso look for that static void main somewhere where that is i put this alsonamed space in that same file again this is copy and paste code it's notsomething you needed change they send your application unless an edge casethat step three step four is we need to
create inside of our class program weneed to create a long reference and what this does is it creates a new instanceof belonging system just go ahead and create private static readonly log fornet dot i log writes that the type and now we need to give it a name typicallyi call it long and i say equals long train at laws' manager that get longernow this is going to ask you for your name of your longer this is where peopleget really confused i say get confuse but they may not actually even know thatthey're confused the way long for now as designed and you create a longer for each classthat you're in you give it a name based
upon the class the area so this case imight get programmed ics is my name that points to this specific class that waylater i can look it which program was i in my longest message no point toprogrammed ics something gets kids but that they don't want to open more thanone login since it doesn't create a problem is thread-safe but if you reallywant to open one lawyer and since your entire application not recommended butif you do what you can do is just give it a generic name and then passed thisinstance around to all of your different pieces here application so the mostbasic thing to do is to give it a generic name based upon waiter atchili's case programmed at ces now when
i change over to new class i have togive it the new classes name and if i had 11 programmed icsa had one in thetest folder then i need to make sure i included the path based upon where it'sat so say / program dot cis and having thetest for aids say / test / ses but that means ourselves for each one of yourclasses there is no way of doing this and that is to use reflection to figureout which class work in and give that the longer to do that we do system flexion method base get current method . declaring tape islong but what this does is it says using
reflection of me this now if you'd usereflection on or if you've read anything about reflection you probably haveobjection radar now is the same one that i have a fresh start in that directionis reflection can be slow so i'm doing this a lot more fun doing this in aresource intensive application this could be a serious problem because someapplication down significantly enough that it's a concern was a coupleresponses to that first of all we're doing this once perclass so not responding up classes at a very high rates and by the classes imean classes actually use the logging library unless you're speaking of hisclasses at a very high rate that
reflection is a very very very tiny partof our application in that case is not be a big deal second it makes our application lesslikely to break in case of change for example what if i aside happened on roadafter a footlong in taiwan change denier programmed ics to be my apt icis thatwould change the class name but it wouldn't change a static string rainhere we're now this would pick up that new class name in long as such it maysound each case and really it is but it does make life simple in the fact that ican just copy and paste this exact line into every one of my classes that i needloving but there is a new feature in
dotnet four point six then meets themiddle of both of these methods and show you that in a little bit once we get thelonging working so it's been a long working and they will come back and seehow we might go to tweak this to be a little more efficient but yet still be asimple as possible ok so now with credit save and now i've done step for step onewas we had that new package step 2 was we modified all the configuration step 3we add assembly reference in step 4 is we add this long property leases withone step to go to finish out and that step is to actually log something sodown here and we're gonna say lawn fastest rate here so if you change thelonger it be longer down here so long
died in his response if i what type ofmessage logging so i can say long dads error so here i am saying this messagewhatever it is this is my error message this message is an error i want right tomy appender in this case the console vendor so i missed a console right linehello world and then gonna log error to console that says this is my errormessage let's see how this works run i have hello world and i have thisstream right here have my time i had the thread that i'm on i have the type oflaw to message this case an error and then i have this is my terrorists suchknow that if we look down here this is my error message that's the actualmessage gets written now and the rest
this information is pulled from thesystem a south if you go back and look at that conversion pattern we see thatdate with a thread the loglevel the message and then we didn't give it anexception information so that's how you use long for a net to write to theconsole pretty simple but from here we can move on to a more in-depth example natalie have locking working this one thing wheni go back dress and that is the section right here where it's the reflectionremember i said that we're looking at different way of doing this and this isthe one section that's to.net 4.6% pic
ok so if you're using the.net 4.5 ourprevious then you're not able to use this matter i use so if if that's thecase continues the reflection or type out your own name here but if you'redone at four point six are beyond the headlines create a new class called thislog helper class and i'm going to create a new method called public standing longfor net died i long it was going to turn get longer now here's the tricky part dotnet four points 6 has a attributecalled caller file path now he uses controlled and the using statement forsystem . runtime . compiler services have been called caller file path andthen we give it
string filename equals empty string inso what this does is it's an optional parameter and if we don't add somethingto the filing then i don't fault the car file path attribute takes over and givesus the path to the file is calling this method now has the full path so keepthat in mind we are storing information your story a full path or file that alsomeans that if you have two classes in one file same file path for both of them but ifhe follows standard convention of having one class per file then you'll be fine in here we're going to return that . logmanager . get longer then here for name
in passing by on them and that's itevery time i call this get longer method we're going to instantiate a newinstance of the longer with this file name of the file name from where thismethod was called not harassment is located so i see as inaction and comeback over here and right now i'm still using the old reflection method ofgetting my name but let's see where that what that does first base line before wemake a change go ahead hit run as you can see we don'thave any spot he was telling us where that long messages coming from we don'tsee a program that csi we're here so we go ahead and change our vendor to makesure that we're displaying where that
information came from go ahead and closethis changer pender comeback tour afterconfig and goes conversion pattern right now i'm saying then i want to date thethreat it's on the level meaning error info or debug and the actual message andpassing it along with the new line the exception if there is one instead ofseeing this thread let's go ahead and change this to be the longer the longeris our long source aware that the law is coming from sophie runs program again weshould see the console you i dot program case namespace in the class name forwhich this log messages error was called network capturing that information todisplay it let's go ahead and change
this to use our stack classes to showfirst that's coming this out an extra bonus a long healthier dietsget longer and that gray simplifies the log call makes it much easier to readand it makes it much easier copy and paste without fear no the best does notallow us to stop the practice of copping this one's per class we still have onceper class in order to get them longer need to be changed based on where thelaw is called from let's go ahead and run us again this time i see something abit different in sidebar square braces we have the full path to our program dotcis file what this is doing is it saying this is where the file was when i wascompiled so that's a bit different from
our namespace . classname we hadprevious with the council you i dot program but this can be pretty helpfulin a fact that is telling us which file to look at when you are looking to debugso for those are you running dotnet four points 6 or above that's an optioninstead of using reflection now we have longed for networking we'regoing back through and look at each of our sanctions and expanded into a morefull featured section so for example what we're gonna do right now is look atthose offenders in the apt i config we start with just one offender it was theconsole offender that's great for testing and this may even be somethingyou use and production to paying
circumstance but probably this is notthe only appender you want to use ever so in this section we're gonna expandout what other penders there are and we are wrapped the section up by looking atthe list on the apache web site dead covers all the different vendorsthat are available the first opponent is the file appender name given his fileappender again that's something you can't blame yourself but for consistencysake i like to keep it similar to the same as the name that long for ticketsto the name is filed under and the type is long for net dot tender filed under inside here first thing ashe thanked called file with the value of
the name of our log file story this on ccolin / logs / my log file that txt and then i say append to file equals true wedon't overwrite this one go ahead and enter the file is time and a lot hemodel type equals by gender file appender +minimal clothes that out what this tells us is that we want to ensure that we canwrite this long file easily especially from multiple different locationswithout stepping on toes 30 had trent lott this as little as possible the filethrough my dad right now is our layout type in this is very very similar tothis right here in fact it's the same as up here unless you want change how thelayout looks in this case we don't want
copy and paste so now the way the logactually print out in the text file is the same as it will print out thecommand line we could get into changes conversion pattern and a little furtheron this course we will talk about different layouts and different ways toget information either system but for right now we're going to the samepattern since we're not worrying too much about the layout pattern yet we'rejust trying to figure out how these different vendors work the last 90 hereis we could also add a filter in here to say which type of long statements givewritten to the text file but we're not gonna do that here talk about filters
a little later so we're asking say thateverything just launched as long as it passes this check down here where thelevel set a debug member debugger and higher just logged right now i reallylike that for a while now so we have now completed our first new appender thefile appender before his can see as an action you come down his roots sectionand add this as appended to be used so tender dash raf equals file under your spell it right and thatshould be it let's go ahead and test out this new pender your head and resizethis folder open over here to my logs folder and for his starts opens up in mylife how is created and we have a
message on screen and 24 to go way iwanted it yet because open up this text files compare looks very similar so ihave the the time i have the location is case the program that cis type which iserror and this is my error message so will the same ones you sent a text fileones in a console now if i close this out i start over again only have onelong message here because it's a new console window open up my log file diedtxt i have two messages says when the benefits of city to attacks by so that'sthe file appender now there's one flaw that you may notice with this and thatis that this file will grow unlimited because the long run this application tomore than get handed us text file it's
never clean itself out well this next appended a look at willhelp us with that was next up under this rare call rolling file type is 14 penderrolling file appender inside here we're still here filename sofile name equals c colin backlash logs / rolling file txt si tend to file valuetrue i say they're rolling style i'll be size so its gonna say that go in newfile every time we hit this size maximum file size value equals 10 cents to onesource file get a ten megabytes we close out star in the next century ad here isour max size backups in this valuable asset to befive so what this does is it says i want
a maximum of five of these up to 10megabyte files so we have here it is once our rolling file long dat txt hitsthe 10 major by mark wright one more entry into it then a system is going torename this file rolling file law got txt . one and create a new rolling filelogged out txt once that wrong file logged out txt it's the 10 megabyte markit's going to rename rolling file long time txt 2012 be rolling file logged outtxt . to its name the currently full 13 rolling file long died txt doubt one isgoing to create a new ruling file on that txt once it has buy extra files sowe have our cars got one dot to dot 3 darfur and died 5 when the currentruling filed that txt which is always a
lazy nation when that when his ten megabytesdrop top 5 gonna kill the file and then made up for us $5 $3 for a list and thenmakes a new rolling file long that txt your latest day is always in the fileyou named a rolling file long dead txt the next newest data isn't adopt one andthen always down till defy was the oldest daughter you have stored so thiscase around store ten megabytes in each of those files or have five backup filesso once we have a full backup set once you've exceeded our maximum storagecapacity we could have anywhere between 50 and 60 megabytes worth of data as itstands right now
next we're gonna say more i don't bestatic log file name is true in this is make sure that the founding doesn'tchange now last thing i do is copy and paste our layout is it the same and sothat's one to get used to how painter's work really is just copy and paste andthen we just modify that things that are different for specific offender in thiscase the file name is the same for both the rolling file appender and a fileappender they both have attained co-founding any both have the idea of apain to file versus over a new file there are some variations based upon thetype so little more specific the rolling file appender that does the fileappender but basically these offenders
are about the same before you go on lookat something a little bit different little bit outside the norm for filedefenders i wanna go ahead make sure we see this action cases go ahead and safethree sizes again and one last thing before we forget we have to come down tothe 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 seemsto happen this is the part of the episode i did call find his mistake andgo back and look at our config something is wrong he spied a year pursuing youmay pick up really quickly for others it
may take longer but you look hereremember i said he's a similar this appender and this appender have a lot ofsimilarities there lay out the same the files the same but look up here in suchfile value equals and down here file name equals i was talking whiletyping and came out as name instead of value was tries again run and now i havea ruling filed long dead txt called out and look at our file long it looks veryvery similar to our list just now this one has one entry whereas this one hasmultiple alright so that is the rolling file under very similar to the fileappender i would recommend however that if you're going too long to text filethat you use the rolling file appender
you don't get burned with a server thatclogs up with a massive text file even here fairly certain he'll come back tothat file and get rid of it everyone so i'll make sure it stays small you reallydon't wanna help file they can grow without end so i get rolling file tenderand always just keep it delete old files that way if you don't get to somethingor if you get an error in a loop and just keep spinning up issue after issuelong in the log file you don't shut down your computer or server this nextappender can get a bit tedious to type out your head and copy and paste a walkyou through each thing does start out with the appender name equals ato netoffender and a type that
under 8000 under all rights in herebased in my code and that's a lot of course let's go back and look at whatdoes the very first thing while jack is the buffer size the ato dotnet genderrights to any radio data source in this case writing the sequel server so thisright here is one of those guaranteed thing that will trip if you copy andpaste someone else's config i have seen a number of questions from people eitheron stack overflow our code product or elsewhere were saying my ato dotnetappender does not work i've tried it i tried the text layout and it works itried to rolling tax it works and i come to ato and nothing works always comesback to are almost always comes back to
this buffer size so what this buffersize is it a sad instead of writing a query to sequel server every time wehave a long message to wait until i bill a buffer so in this case after 10 logmessages have been written on your right all ten of those two single server andthat just keeps the traffic down a single server the kicker here is bydefault whenever you see a demonstration on lineor even at the long for an essay that if it will be hundreds you have to write ahundred log messages before any of them show up in your single server now whenyou do close out your application though supposedly written to single server soif you're watching us applications open
you may i see anything we close it youmay see those ten twenty thirty long messages written a single server at thattime my recommendation for demo purposes isthat you set this to one that way every time i log message gets ripped theserver you see it in highlighting times it may put extra strain your singleserver but nothing that it's not able to handle the production values in privatemuch higher than this but we're really depends on your scenario for instance ifyou rely on up to the minute reporting on your errors in the logs then erosionhave this is lowest possible maybe even one because if a system does not write along message very often and you have a
608 maybe hours or even days before thatbuckets filled up waiting days to find out the you have an issue is not idealfor demonstration of keepers at one the next thing is our connection type inthis says hey we're use a sequel server connection and feel free copy and pastethis this is a whole bunch of stuff that no-one memorizes next we had aconnection string and this just says helicopter database in this case and cutinto the local database or dot the catalog amusing is my my database itselfthat's application to be and then using the integrated security which means itgoing to use my login as the security from a single server
next is the command text this is theactual query to run in this case let's get down to hear the command typist textthat means i'm running a raw sequels to in this case an insert statement so i'msaying insert into the table logs here's the columns to use and then here's thevalues to put in them now there is an alternate that's much easier to do inthis file is also in my opinion better practice and that is to use a storedprocedure so instead these two lines are living here for now to show you adifference but you would play its command text value would be the storeprocedure name and that's it and and the command type the value equals storedprocedure so you wouldn't put both of
these in here this one and this one youchoose one so either had a like that where you had it like that personally i like this method betterbecause it's so concise out to type all this out i can also do things are storedprocedures such as having extra statements around my insert or making anupsurge statement so that if it's already a statement there that matchesthis which shouldn't be but if there is we could do an update 7 answer there's anumber of things we can do in store procedure but size just the actualinsert but i use it is up to you so choose used or procedure or the actualcommand text go ahead and take this out
both work the same way so i can youdemonstrate both big deal both work against you for your call i'm gonna showyou one more thing and that is the parameters right here these match up tothese parameters down here now in a stored procedure takes parameters andtheir named just like this but we don't you specify them because they arespecified for us but for the insert statement whereas just taxed i have tospecify the parameters so that is one thing i know is that we have to actuallyspecify the parameters passed in in weird again passed in alright let's backout so we have a number of parameters down here let's go through them whenthey won the first parameter is the at
log underscore dates between specificparameter name that d be type in this case it's a datetime tape now this is ac sharp type not a sequel type so no this datetime not daytime too was when iactually story in in the database next is the layout this looks veryfamiliar if you're looking up here was there is needed this only instead duringthe pattern layout i am doing the wrong time stamp lay out the timestamp for hislog entry and so instead of specifying the conversion pattern here it justknows ok you're at the time stamp on give it to you that is a bit of adeviation from what we're doing up here we could do that we could take us outinstead put a layout that uses the
percent date absolute but that's a lotof the dvd a little bit and show how it looked a little bit different our next parameter is the at logunderscore thread and this is a type in see strength now in cstring identifiesbar chart if you're familiar with sequel is to type of string feels akin storythere are two major types the first type is march are annexed is nvarchar barchart is a variable-length strength whereas in march are is still availablethanks drink but it can store unicode characters in this case i said i don'tthink i need to store unicode characters in my database therefore i'm they uselarge garfield's and so we have to
passing and c string as the type if wewere storing nvarchar are considered an cstring we would just do strength sothat's the difference the size is the size in our database inthis case of 50 characters and then this should be layout pattern just like uphere to lay out pattern can be very complex plots this is the layout patternfor one field i'm storing each field in a separate column therefore it's veryvery simple here i'm just story but thread to come down here to the nextitem we have log level it's an ancestry as well against it the characters inthis just stores the level and that's our debug error warned fatal or involvethe next one log source that's the
location with a longer in it and so imade that 300 characters long and the pattern is just that percent longer nextwe have actual message this is what we send when we call log and still industryand its four thousand characters very large but you make sure that benefit youcould do in march our macs which is much larger if you want you but in this casei say you know what 4000 characters is planning to that's about shoes and findout here we have the exception against ring again 4000 characters and thelayout type instead of being one of these items i'm saying give me theexception layout so these are the fields and inserting into my store procedurenote that we don't have to put just 11
a.m. into anyone field and we don't haveto use it just once so you could get creative in here wheremaybe you rate each item to its own column but then the end have a columnthat is the printed lawyer what you would see a tax policy like backwardsthe combined file what you write the database is totally up to you used tomake sure that your insert statement or your store procedure will take thatinformation and so speaking of stored procedures let's go ahead and look atour store procedure first here's my table this is the logstable its me application tv and i have i d along date with red the level thesource the message and the exception so
i did know the varchar sizes match upwith what we have in our web config file next i create a stored procedure thattakes those same names and inserts them and there's an insert statement doesnothing different than what we originally had with the insert statementfor the command text but now i have it wrapped in a stored procedure finally ifyou come over here to this window i had a slow start from logs if i run this isee that have no entries so far let's go ahead and change that will come backover here we come down here to our roots section and add this appender and that's double check that insurancerate adr net under so we should be good
let's run us i have message on thescreen but come back over here to sequencer i r us again i now have oneentry date there's a date and time there's a thread number there's the loglevel there's a source it came from and there's the message and we don't haveexception so in just a few moments we were able to use this pattern to write asequel database now we're starting to get into things that can be more usefulin a production environments now we have to arrange a single server let's look atother 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 thislong for net
appender and you know every time we havecreated pender it's always been lost for net pender . something so go ahead andopen that up and as a whole list of things in here and we look down here wehave these file appender class and it will tell you all about the fileappender it's not great but it is something and you some clues as well doit also gives you an idea that you can do a file appender which we already knewbut there are other painters and here you might not have known about forexample the ansi color terminal appender i've never used that there's also thebuffering appender skeleton buffering 14 pender may not useful for you and yourcase but there's others in here that
might be for example there's theeventlog appender this rights to the windows event log it's something thatsounds great but i would recommend against trying to use in too manysituations there are situations where it's right but the most part it's not great in thereason i say that because you have to have special permissions for the use ofits running this application so if this is a web application typically you'rerunning under the asp.net account if you are under that account you either have to change thepermissions that account which i don't
recommend in order to get more rights oryou have to write to the event log once using in mister account in order thenkind of allow that to be written from then on using the asp.net account itslittle clunky but it does have its purposes another one it has its purposes thatmaybe a little clunky for you but it may be perfect or somebody else is the smtpappender this will allow you to send emails out whenever you have a longfeiler in my advice here is to make sure the only sending emails out when youabsolutely need to don't send emails out saying yes i gotthis piece of code especially if it's a
little especially if you're saying thatyour boss this is just one more wave it you can do something with technologythat you probably shouldn't so i would encourage you to look through here lookvery different vendors find ones that maybe you want to use or that fit yourcertain scenario where you think they might and then go find examples of howto use them and there are examples in here if you come down to configureexamples we can scroll down find there's the ms eagle server example isn't accessexample both he's an ato net appender in this case the access one versus thegeneric one for the single server is oracle oracle as a whole bunch more inhere and you can go through and not only
see asp net race offender but also howto use it if we come back up to a single server one you'll note that the buffersize is set to a hundred so as make sure that you take whatever information youget in here with a grain of salt it may be a valid setting but may not bethe same that's right for you in so that wraps up our sectionon tenders we've gone through identified each of the major types of tenders andalso where to find out more information about other alleged case of vendorsnextel look at filters if we come down here to the bottom we have this onefilter it says only give me items from deep above but they're more houses wecan add to our panders to limit what
information they get so let's get tothat now before you get in a setting up ourfilters i want to a little bit of housecleaning first let's go ahead andcollapse over a penders lee better-looking file here only theconsole appender open and we're just going to use the console for now let'sgo ahead and comment out these other three offenders from meused no i'm just commenting them out from the roots action i don't need toactually change the offenders themselves if an appender isn't mentioned in asroot section then it won't be called for now and just the console offender here ihave just the console penned up here
let's come back to the program dot cisand let's make a few changes here in order to have more log statements personto leave the ones we have and then start creating new ones say long does debugthat's the lowest level message so far this whereas a developer colon tutorialwas right next let's do lawn dads info is the next level up it will saymaintenance water turned on next law that one says it remains as well and will say thewire is getting hot now for the long . error which the next level up butactually create an air bar equals 0 do a try and make this divide by 0 exceptionand here if we throw a divide by zero
and do a long day error is happier can be involved want todebug if you want it just makes sense logically usually if you're throwing anerror and error thrown you that you call an area long statements again it's up toyou if you want say it's only for debug or this error message isn't a bad onethat's fine in his case was calling dr message and then here actually include theexception to this is one of those things that i told you about but you haven'tseen yet and that's the idea of him pass exceptional long as well
back over here after i can we have thisnew line and then the exception and so far has been black but now we'reactually use it so that's a reception let's go ahead and create the exceptionby saying they are x equals 10/10 since i 0 exception last and highest only longscale is along that fatal explode ok i have five log messages in increasingorder of severity so from the blog the lowest involved in warren an error thenthey'll first let's make sure they all run alright i have a bit of a mess herein the reason why is because i'm logging out this very very long path to aprogram that cis so what's changed that
lets get back the reflection method wasonce again and now it's a lot better it's a little shorter in fact you cantrust message down even more so let's go ahead and go back to our apt aconviction say you know what we're gonna i just as conversion pattern to onlygive us the level and the message where the interconversion patterns more in thelab pattern in a little bit before now we can just tremendous message make alittle simpler again and now we have a little better system we have debug infowarning error and then underneath the air we actually have the exception andhas fail so since you haven't seen accession before let's look at it wehave the airline says developer we try
to divide by zero again we have a newline and now we have exception message exception is system . divide by 0session attempted to divide by zero and then just leave whereas at 125 in theprogram to ics so i can be really great debugging information for when you havean issue since we just want the actual information on the screen now let's goahead and take out the exception we know can do it we don't have to do it againand now we have a very clean screen that has just five things on it and in theorder from debug their fatal that's a great setup for teaching us how tofilter out different items there's a number of different ways we can filterdefender we're gonna touch on the most
popular the most used and then there aresome extra ones we can go look at later on the documentation so let's start bycreating section called filter the first built around do is the level rangefilter so type equals one for her that level range filter and this has 2entries in it first we have the a-level how is blankfor now and then we have the max now leave it blank as well for now so littleman and a level max are be brackets around which you want to capture yourblog entries remember that debug is the lowest infatal is the highest so if we only want to capture warren and error messages thelow the men will be warned and then max
will be error what this says is hasreleased a warning level and it can be any higher than error message whichmeans that we're not going to capture the debugger info and we're not going tocapture the fatal what's runs and see how it works merry go we have worn and we have errorbut that's it the rest of them don't get along just console instance right nowthe console is the only appended it's actually logging they didn't get alongthat are at first that may sound bad thing you're longing messages that don'tget captured anywhere but think that one through four minute if you put a bunchof statements in your code that are long
done debug and it only for debuggingyour application you don't want those debug messages story where most likelyunless you have a problem then you coming in here just your filter to sayyes give me debug messages so we can justice again if you want if you wannainclude up through fail because change the max the fatal and now we have threestatements war on terror in fatal so that's the level range filter this isone of the few filters that if it does not fall within its boundaries the logmessage does not get written imma go ahead and comment this out and createnew filter that way you can see how each filter works in my code to create a newone in this one is going to be filter
type equals 14 net dot filtered througha string match filter so that's good i do it in a match the string patterninside of our log message so string to match value equals and let's say hasmaintenance to now only maintenance messages with a lot right we'll find outand we had a lot more than just minutes messages if we look through as managerswe see no reference to maintenance in the error or the debug message and yetall five are showing up why is that well remember with the rangei said this is one the only ones that if the message falls outside of that rangeit does not log in this case it matched maintenance on three of those entriesbefore the other to it didn't match and
it fell through to the next filter sincethere are no more filters it assumed we want to log it seems counterintuitivebecause it feels like we want to not include something if it didn't matter shelter but the reason we do this isbecause you can have more than one cell filters inside of an appender but if youwant just match on this filter you have to create onemore filter at the end of type filter that mean i thought there was nothinginside this is the if you get here you are done don't log so now it's going tomatch the maintenance training and it doesn't find it is good i dropped out ofthe next filter the next order says
don't log was stress again ok now weonly have three statements and all three are making statements you should alsotell you something important about the filters order is important it matchesagainst the first filter if it doesn't match it will typically drop down to thenext filter the exception being the level range doctor if it doesn't matchhere it's done so that means if i move this filter the denial felt there abovethe string matched filter iraq again nothing that's because thefirst built in a match was this deny all filter so it's moving back down to thebottom 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 exceptits matching on a level surface level to match value equals error this is onlygoing to grab the error level but it does fall through just to stream matchedfilter which means that we have to continue to have this than i are at thebottom but see it in action all right there is just the errormessage let's get a little more tricky and create another level match dr. copyand paste this and say i only want debug messages so now i have all the care anddebug remember these fall through so it's not an error
falls down the next one it says are youdebug its runs again and now i have two statements the debug statement and theareas that there might be times when you wanna captured two of the five and theyaren't right next to each other so all debug messages but also failed messagesas well so as you can see their main different ways we can configure ourfilters to pull out exactly what we want from any situation next week i'll lookat the lawn patterns the information actually write out to the database wouldtax file the screen will look at the different pieces of information we canpull from a system in a drawbacks associated with gathering backinformation
now let's dive in that logging patternthe strength gets printed out a screen or get store the text file right now wehave just the level and the message and then new lion exception in ourconversion pattern or that logging pattern let's go ahead and clean up acouple things here first before we make some modifications to this first goahead and comment out all these battles go ahead and movethem we don't need any more so since have removed all my filters everythingwill get printed out now know we still have this down here that says debugginghigher if i change this to error it only print out error and hired even though idon't have built up here just
demonstrate right now i run this i haveall five messages my debug info warn error and fail but if i change this tosay error iraq can only see the air and fatal message for our purposes let's goahead and change it one level higher cause a fatal now only capturing onemessage just that fatal message saying the water pump exploit that's goodenough for testing purposes because what we're going to concentrate on is thisconversion pattern now you've already seen the standard pattern so for examplethe date the longer the level the message the new line and the exceptionis a pretty standard and trees as a few more standard ones for example we had atone point the thread but it's a few
extras we can add i'm gonna use the newline after each entry so we know what we're looking at first legal level herewith us a level and then put new light at the end ofnext year as a message that we're at take out exception that gets a start werun that we now see levels fatal and message is maintenance water pumpexplode now we do have an extra space there was take that out again we shouldsee one per line laid out nice so it's a few extra thingsone line per time so we know we're looking at the next one is the utc didput utc date and we'll do that well this is just like the date only as in if theutd
compare this was put a new line and thenput the date certain date and make their absolute well okay so wehave the utc day and the record date as go ahead run us now for comparison wehave the level message would be recovered the utc date is 05 3943 thedate is 01 3943 so i'm four hours off of utc time next let's add the timestampthis was a bit confusing for people not quite sure what what information isgiving them in this case 149 its rise again announced so what is that well i am put the new line of go aheadand put them in their first before you start talking about it and that's 110 sowhat is that times there were times them
is the number of milliseconds since theapplication started their situations that can be very useful now is when weget into the deeper waters the things that aren't as straightforward or aren'tas efficient these things so far fairly efficient when it comes to rain to thelaw new line and we're going to add two newpieces of information first one is the identity in a square poll from the principaldenied any dat mean property and the second one is the user name that username polls from the winner's identity property so these to rate here can be abit slow and they can also sometimes
give you non information or be empty let's go ahead and run this second cdidentify mind is blank and yet the user name is office tower / team was that'smy login name sort of paying environment this may be great information or it maybe non information so just be aware that might not always show up the way you'reexpecting it to this is doubly true we're talking about a web serverremember that this application runs typically on the asp net account in thatcase username will probably be asp net username not the name of the user loginnext there are few entries they can pinpoint where in the code we had theproblem first let's look at the location
and this is the location the code wherethere's a problem now in order for the system know this you have to have thedebug information it works a lot better and debugging that was in the productionenvironment just the line number same thing here as far as working better anddebug and doesn't production and finally we want to pull the method name againseems cleaner so in this case since i'm running in debug mode in visual studioit knows them running from programmed ics it knows on line 32 and the methodis the main method these last three can be very very useful when you'redebugging just be very clear that this is going to work great in debug on yourmachine going into production you may
find non day here you may find it emptymay find information it doesn't quite make sense because it doesn't have thereference to pull from the right locations so that's a brief overview ofthe more advanced i am so you can log beside the on the rt covered but we'renot quite done yet we also have the option to pad or shrink down ourinformation remember we're adding information todatabase we said that a log message shouldn't be more than 4000 charactersor that exception information shouldn't be more than 4000 characters what would happen if we had more than4000 characters that be a problem trying
to put that into the database well long for now has an option for thatif we come back here lets choose the message itself unless it a messageshould only be five characters long now that's obviously not a real-worldscenario but that will give us an obvious to the matter we say topped 5that dot 5 indicates that the message at most g5 characters if it's more than thatit's gonna start trimming off from the left as an action so my message is lodok that's the part of the word for exploded the reason is hello dee dee andnot
mhm tv was at the beginning of themessage that's because we capture the end of the message everything else istrimmed off so if you go over your five character limit in this case the firstpart of message kids to lead that isn't something you can change a settingthat's one of those things that could be done all better in long for now i wouldlike it where you would add the first part of the message and then trim at theend but that's a nigga do in code or even make a interface for your logmessage that goes ahead and trims off the end of it it's definitely doable isjust not something that's built in to be done with 14 that ok there's a couplemore options we can do here we can put
numbers before this died in this wouldbe the minimum number of characters so if i puts in here a minimum of 20characters and a maximum of five characters what is going to do is isgoing to trim off anything 15 characters but if it's less than five characterssay it's one character it's going to add a space in that space is going to go andthe left hand side of your message so if i had just an each in a sealed its gonnabe space age because i have that too there if i had yellow exclamation pointbecause it's six characters it was say hello e l l o exclamation point so those twocan work in conjunction with the spacing
if i instead put a negative sign from itthat's going to put the spacing at the end so again might just in each in thatmessage it would be each space inside the space age so if you doing a space tolimit text file you could make sure that yourminimums and maximums of the same and then anything less get spaces anythingmore gets cut off and that's all there reallyis to logging information out to our file a layout that we like that's theconversion pattern now have a handle on all the information that long for netprovides forest and hits log messages let's take a look at how we can bring inour 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 bitof extra information you could bring in the message but maybe why and differentfield or maybe using that ato dotnet appender where you want put in differentcolumn if that's the case there is a way to bring information in let's start bycleaning up our conversion pattern here let's just do the message itself looksok we just have maintenance water pump exploded that's fine for now let's goover to our program and we have these five messages only this one is beingpulled because it's a fatal message and
that's the only ones that we're pullingin using this long level so let's create a loop down here in here and do a forloop yes a 12 lasted five which means zero one two three and four so it's fivetill now just and we're going to say long . fatal this is message number andthe eye of the end and actually we're gonna change that from somethingdifferent because we're already using i up here or just take away thedeclaration has already is okay so we have i 0 ice less than five as long asfive messages we can go ahead and commenters out so now we have fivefailed messages that say this is message number zero one two three and four runsand find out okay so you have this is
message number zero one two three andfour well maybe we don't want to have that inthe message itself maybe i say something a little more generic like this is as afatal error in the process and may want capture that that i informationsomewhere else the way it do this is to use theproperties of water for now we come here and say long for that god global contextand there are multiple contacts there's the global contacts in thisthread contacts and go through a list here and see all the different contextsa logical thread context these are all scopes so the tighter the scope the morelikely it is to be captured so for
example if i have something a propertyname in both the global scope and in the logical thread scope then the logicalthread scopes variable is over right what's the global scope that can getreally complicated don't worry about it if you don't know which scooped you wantuse a global scope that will work across the entire application the smaller onesare for specific threads typical so as to you global context . properties and now youcan specify or own property let's call this property the counterproperty and we're say this equals the current diet i know we can put any kindof strange information into this
property which also put other types ofdavid in here and we'll get to that in a minute before right now we're going tostore i and that's it we don't actually change our log message because we havenow created new variable we can pull in in this conversion pattern so let's go ahead and pull out in soinstead of having it in a message i'm going to say the number dash the message so let's start with ourpercent sign and then we save property and they get the name in our casescounter creators so we have percent propertycurly braces the name of your property
but when you called it and i'll put mydash here and that's run this so now i have zero one two three and four withinthe dash and then the message is a big difference because i could have put thatin the message itself but the difference is i now have this as a separateproperty i can pull in different way so i have made a deal yet tender i can putthat in different field now we're done here is just past the value of and i dottostring got the information is stored as text but there is a way to have idon't panic property so let's set that up and overhere and create a new class and i call this class the counter class public
and one profits into property call thiscounter so it is going to store the information that loop so i 01234 willstore all in this number here and last night to a public override stringtostring and returning the base that strength i mean to say that i want theloop counter to strength so whenever you call this class and say . to string aclass instance instead of returning the class name which is standard for a classinstance it's going to return the string value of the loop counter into variableso can save that come back over here too are programmed at ces declare and new variable called counterrecall this hour i asked oj since we
haven't i j equals new counter next moveout this global context out of my loop and pasted up here when i was in my lubeit reassigned as property every town went through now and when i say it onceso instead of assigning it a variable was just in a science jay jay is theinstance of my counter class now whenever j changes the two string valueis remember two strains actually just that loop counter wherever it changesits going to change the property and long for now shut down here i makethings a little messy don't do is in production jade outlook count equals zero and thenjade luke hour or less than five and
then jade care plus plus sorry place that ivariable with the property counter using my instance call jaythat's all i've done i've moved this outside of my lips are only get a signedonce its rise again and there you go it looks like nothing has changed except inonly a sign that property once it picked up the changes using that tostringmethod so great right as it is this is definitely a test just show up where cando but what this demonstrates is that you could create some sort of propertyor some sort of class instance they captured information or send informationto log for net based upon certain
circumstances in your application danyou justice it once in that global context and in your configuration youcan pull that property over and over and over again and will always get thelatest information a little more advanced it's not something you use anevery application but where you want it it can be a great help so they are acouple ways you can get the most out of your long for net using some advancedlogging techniques now let's review what we've learned and see where we go fromhere so that's the basics and the moreadvanced topics of long-term debt really once you break it down it's quite simplewe started off with those five steps to
get long for networks first adding ourreference using nougat too long for net application next we went into ourprogram dot csn add this entry right here which is once per application thenwe add this team right here which happens once per class or once per timeyou want to instantiate you don't have to once per class if you don't want toend then we moved on to creating this config section so we created thissection regular says hey i'm along for next section and then in that longbrunette section we add our vendors some with filters some with differentconversion patterns then we came down here and add our roots section whichpoints out which offenders are working
and then with the overall filteringlevel is finally we create these long statements that log information to logfor net as long as it accepts them to wrap up we create some advanced data toolong to our long for instance we create dynamic property using our classinstance allow us to our can fix it pull the information dynamically based upon the point in timeit which was called so that's long for net very very simple at the end of dayyou just want to create these long statements you pepper these throughoutyour application where you need them at the level you need them since he knowhow to filter and how to limit which
long statements get logged to yourlawyer appender source will it be the text file database or even a consolewindow you can mix and match and play with these things for example you mayhave a console window you don't care for scrolls like crazyand see send all her did to it where you have your single database the protect alittle more and he only rate warnings above and find that text file whichmight be a backup for your single server but you only want to write the exceptiondata errors and the fatal injuries he may say you know what i mean a rollingfile because it's just a backup and i want to only keep a hundred megabyteswords of miles across 10 files based on
what we've learned this course that'sdefinitely possible it's possible using the example we've already done just torecap this video is a companion piece of the article i wrote on the log for nettutorial so all the information we've gone over here in this video can befound in some format in this article so if you want the written copy of it goahead and go here if you want more information from a source you can go tothe apache log for net site and get the sdk reference or the how to's or evenconceive examples for dependency you want that's really all there is for longfor now i encourage you to play around try things out
build a dental out and then once youhave your config file the way you want to go ahead and convert any productionuse these things whatever you want to capture information inside your runningapplication down the description you will see links to always different sitesyou will also see a link to the gift of a positive re where all of the code iwent through in this course is start if you look you'll see that the code hasbeen tagged at various levels for each of the different sections in this videoyou can download code back to where it was at that specific section also if youlike this video if you want to find out more information on other providing bothhere on youtube in other places as well
go ahead and sign up for my newsletter idon't spend a lot of emails out the way do i tell you about the new and upcomingcourses than creating and i also ask for your feedback i love hearing from youwhat you're looking for your feedback shapes these courses so please let meknow what you'd like to see next thanks enjoy using log for net without beingafraid that config file
0 komentar:
Posting Komentar