Logging in Java with slf4j.docx

上传人:b****5 文档编号:12176957 上传时间:2023-04-17 格式:DOCX 页数:14 大小:73.81KB
下载 相关 举报
Logging in Java with slf4j.docx_第1页
第1页 / 共14页
Logging in Java with slf4j.docx_第2页
第2页 / 共14页
Logging in Java with slf4j.docx_第3页
第3页 / 共14页
Logging in Java with slf4j.docx_第4页
第4页 / 共14页
Logging in Java with slf4j.docx_第5页
第5页 / 共14页
点击查看更多>>
下载资源
资源描述

Logging in Java with slf4j.docx

《Logging in Java with slf4j.docx》由会员分享,可在线阅读,更多相关《Logging in Java with slf4j.docx(14页珍藏版)》请在冰豆网上搜索。

Logging in Java with slf4j.docx

LogginginJavawithslf4j

LogginginJavawithslf4j

ThisdocumentisanintroductorytextteachingnewJavaprogrammershowtologinformationabouttheirprograms,andhowtoreadtheinformationloggedfordebuggingpurposes. ThisisdemonstratedwithfullyfunctionalprogramsusingthesimplestpossibleconfigurationofSimpleLoggingFacadeforJavafrontend.  Evensothemethologiesshownaresuitableforfullscaleproduction. 

Pleaseprovidefeedbackifyouliketo ravn@ 

--ThorbjørnRavnAndersen 

Tellingyourgrandmotherwhatyoudo

Welcometotheworldofprogramming!

 

Hopefullyyou'llenjoyyourstay,andperhapsevenwanttolivehere.    Ifyoudoso,andyoueverneedtotellyourgrandmotherwhatyoudoforalivingthendon'tdespair. Justaskherwhat 

"Bindoff6(7,7,9)stsatbegofnext2rows. DecRow(RS):

 K2,k2tog,kacrosstolast4sts,ssk,k2.RepDecRoweveryotherrow10(12,13,14)timesmore--38(40,46,48)sts.Continueeventoapprox211/2(22,221/2,23)inchesfrombegendingwithaWSrow."

means-mostgrandmothersknowthat-andtellheryouwritethosebutforcomputers. She'llnodandunderstandcompletely. 

IfyouarelikemostlearningprogrammersyouhaveNOideawhatthequoteabovemeansatall. Well,itispartofaknittingrecipeforasweater[ 1 ]andthatiswhatprogrammingisbasicallyallabout-writingknittingrecipesforcomputers. 

Programmingisacraftittakesyearstomaster

PeterNorvigwritesinhisonlinearticle TeachYourselfProgramminginTenYears -arecommendedread-thatittakes10yearsorperhaps10000hoursofdeliberatepracticetodevelopexpertiseinanarea.  Forprogrammersthatmeanswritingprogramsandreadingprograms,butunfortunatelythereisnotyetageneraltraditionofexperiencedprogrammersmentoringnewprogrammersinperson,soyouwillhavetolearnalotonyourown.  

Byusingthetechniquesdescribedinthisdocumentyouwillhaveagreaterchancetoavoidsomeveryembarrassingandexhaustingexperiencesinyourfuturejobs,andhopefullynothavingtounlearnahabitortwo. 

Ifyouneedtogetexperiencewhilestudyingorpreparingtogetajob,IwouldrecommendthatyoulocateanOpenSourceprojectwhichyouaregenuinelyinterestedin-forinstanceifyouneeditinyourownprojects-andhelpthem. Thiscanbothbeprogramming,butalsowritingdocumentation-asgooddocumentationrequiresthoroughunderstandingofthesoftwarebeingdocumented. Thisalsogivesyouexperienceworkingwithateamwhichcommunicateelectronicallyandusetoolsthatallowmultipledeveloperstoworkonthesameprojectwithoutdisturbingeachothersfiles. 

BychoosinganOpenSourceprojectyoucandemonstratewhatyouhavedonetoafutureemployeraspartoftheinterviewiftheyaskwhatexperienceyouhave. 

"Andyoutryandtelltheyoungpeopleoftodaythat.....theywon'tbelieveyou."

JavawasdesignedbySunMicrosystems,whichhappenedtomakealivingatthetimesellingcomputersrunningtheSundialectoftheUnixoperatingsystem. ItisnotasurprisethenthatJavaprogramstendtolooklikeotherUnixprograms,whichweredesignedtoworkonthecomputeryouseeinthepicturebelow. 

PictureshowsKenThompsonandDennisRitchieworkingatthefirstrealUnixmachine.  Pleasenotethatthereisrealpaperinthe"typewriters",theclosetbehindthemenis the computer,andthatthecircularcontainersontopofthecomputercontainprogramanddataonpapertape. Thingsweredifferentin1973.

UnderUnixeveryprogramhasthreeinput/outputconnectionsavailable-namely 

∙standardinput -thisprovidesthethingstheusertypetotheprogram. (Java:

 System.in)

∙standardoutput -thisisnormalinformation(Java:

 System.out)

∙standarderror -thisisinformationabouterrorsituations(Java:

 System.err)

TheUnixphilosphywasstatedbyMcIlroy[ 3 ]tobe" Writeprogramsthatdoonethinganddoitwell.Writeprogramstoworktogether.Writeprogramstohandletextstreams,becausethatisauniversalinterface. ".Thismeansyoucanlettheoutputofoneprogrambetheinputofanotherprogram-calledapipe -encouragingsmallspecializedprogramsbeingcombinedtocompletealargertask,likecreatingalistofwordsinafilebyfirstextractingallwords,sortingthem,andtheneliminateduplicates. UnfortunatelythishasnotcaughtoninJava,mostlybecausetheJavaenvironmenttakestoolongtostartforsmallprogramstobereallyusable. Theconceptsarestillthesame,however. 

SothesimplestpossibleJavaprogramusesSystem.outtoprintouttheline"HelloWorld":

 

1:

publicclassHelloWorld{

2:

publicstaticvoidmain(String[]args){

3:

System.out.println("HelloWorld");

4:

}

5:

}

Thisshouldbenamed"HelloWorld.java",andiscompilablefromthecommandlinewith"javacHelloWorld.java",andthecompiledclasscanthenbeinvokedwith"javaHelloWorld". 

Line1declaresthistobetheclassnamedHelloWorld-thereisno"package"linesoitisjustHelloWorldinsteadofe.g.com.bigcoorporation.HelloWorld. Line2isthemagicwordsneededtobeabletoinvoketheclassfilefromthecommandlineas"javaHelloWorld".  Line3printstheline"HelloWorld"tostandardoutput. 

Now,whydid that happen?

Oneoftheunfortunatesideeffectsofprogrammingforalivingisthatpeopleareusingyourprograms,andtheytendtofindthatyourprogramsdonotworkas they expect-thisistraditionallycalleda"bug"[ 2 ]-anditisthenyourresponsibilitytoidentifyandcorrecttheproblem. 

Inmostcases,allyouhavetoworkwithistheuserdescribingwhathappenedandwhatwasexpected. Theprogramhasendedandisforallpracticalpurposesunavailabletoyou.  Henceawayofsavinginformationfromwithintheprogramforlaterisneeded,muchinthesamewaythatlogbooksareusedonshipstoaidinnavigation.  Theterm"logging"isusedingeneralfortheprocessofsystematicallysavinginformationforlater. 

SeveralloggingsolutionsareavailabletoJavaprogrammers. Allofthesegenerallysharetheabilitytolog:

∙Theareaofthecodecontainingthelogstatement.

∙Thetimewhenthelogstatementwasinvoked.

∙Animportancelevelofthislogstatement.

∙Anexception(withaccompanyingstacktrace).

∙Alogmessage.

Thishasproventobeveryhelpfulforlogsintendedforthehumanreader. Facilitiesavailableinsomeloggingframeworksinclude:

∙storingeventsinadatabase

∙alertusersbyemail,instantmessagingoranyotherelectronicmeans

(butthatistooadvancedtobecoveredinthisintroduction-itisjusttogiveyouanideaofwhatispossible)

TheHelloWorldprogramrewrittentousetheSLF4Jloggingsolution(fullinstructionsareinappendixA)andputinthe"demo"package,lookslike:

 

==== 

packagedemo;

importorg.slf4j.Logger;

importorg.slf4j.LoggerFactory;

publicclassHelloWorld{

publicstaticvoidmain(String[]args){

Loggerlog=LoggerFactory.getLogger(HelloWorld.class);

log.info("HelloWorld");

}

}

===== 

andgeneratesthefollowingoutput:

 

====

2009-06-0710:

38:

21demo.HelloWorldmain

INFO:

HelloWorld

===== 

Thefirstlinecontainsadateandtimestamp,thenameofthelogger-here"demo.HelloWorld"-andthenameofthemethodcontainingthelog.infostatement-here"main".  Thesecondlinecontainstheimportancelevel-here"INFO"-andthemessagepassed -here"HelloWorld". Notehowmuchofthisinformationwasderivedautomatically!

 

Ifweaddamethodcallwithawait,wecanseethatthetimestampchanges,andthatthemethodnamesinthelogcorrectlyindicatesifthelogstatementisdonefrom"main"or"waitTwoSeconds". 

====

packagedemo;

importorg.slf4j.Logger;

importorg.slf4j.LoggerFactory;

publicclassHelloWorld2{

publicstaticvoidmain(String[]args)throwsException{

Loggerlog=LoggerFactory.getLogger(HelloWorld2.class);

log.info("HelloWorld");

waitTwoSeconds(log);

log.info("Done");

}

privatestaticvoidwaitTwoSeconds(Loggerlog)throwsException{

Thread.sleep(2000);

log.info("Slept2seconds");

}

}

=====

withthefollowingoutput:

=====

2009-06-0710:

53:

52demo.HelloWorld2main

INFO:

HelloWorld

2009-06-0710:

53:

54demo.HelloWorld2waitTwoSeconds

INFO:

Slept2seconds

2009-06-0710:

53:

54demo.HelloWorld2main

INFO:

Done

===== 

Ifyouwereshownthislog,youwouldbeabletodeterminethattheprogramhadrunasexpectedtothestatementlogging"Done"inthemainmethodofdemo.HelloWorld2andyoushouldnotlookforproblemshappeningbeforethatstatement. 

Logginginformationstoredinvariables

Ifyouneedtoaddinformationstoredinavariable,slf4jallowyoutospecifythiswith{}.(Note:

ExampleworkswithJava5andlater) 

====

packagedemo;

importorg.slf4j.Logger;

importorg.slf4j.LoggerFactory;

publicclassZeroToFour{

publicstaticvoidmain(String[]args)throwsException{

Loggerlog=LoggerFactory.getLogger(ZeroToFour.class);

for(inti=0;i<5;i++){

log.info("i={},i*i={}",i,i*i);

}

}

}

==== 

whichoutputs 

====

2009-06-0713:

23:

57demo.ZeroToFourmain

INFO:

i=0,i*i=0

2009-06-0713:

23:

57demo.ZeroToFourmain

INFO:

i=1,i*i=1

2009-06-0713:

23:

57demo.ZeroToFourmain

INFO:

i=2,i*i=4

2009-06-0713:

23:

57demo.ZeroToFourmain

INFO:

i=3,i*i=9

2009-06-0713:

23:

57demo.ZeroToFourmain

INFO:

i=4,i*i=16

==== 

Allobjectscanbeloggedinthisway,andthetoString()methodiscalledtogetthestringtolog.Notethatint,long,double,floats,charsarenotobjects,butthatinJava5andlatertheyareinvisiblyconvertedcorrectly. 

Loggingproblems

Allprogramsregardlessofprogramminglanguagemus

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 高等教育 > 其它

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1