Monday, March 7, 2011

Important of the log file in programming


Important of the log file in programming

What's log file?

Log file is the file program create during it operation and process, this log file is very useful for developer to check and debug the big program.

We can integrate log file very easy through the system.file.io

Sample in vb.net


Private mlogst as system.text.stringbuilder
'function to create log file.
Sub writelog(mlog as string)
  
     Dim logfile as string = "c:\temp\log.txt"
  
     Try
       
          'mlogst is the cache in case that file is busy / can't write the information
          'we can keep and write it later.
       
          If not mlogst is nothing then 

               'mean there is previous log that didn't write, so we write it.

               IO.File.AppendAllText(logfile,mlogst.tostring)

               'after write we empty it.

               mlogst = nothing

          End if

          'write the log information.. 

          IO.File.AppendAllText(logfile,mlog)

     Catch ex as exception

          'if there is error while write the log this time 
          ', we keep in the mlogst for write next time.

          If mlogst is nothing then mlogst = new system.text.stringbuilder

          mlogst.apppend(mlog)

     End try

End sub


//// to use…


Sub main


     Writelog ("starting program…")

     Do …..

     Writelog ("doing stuff…"

     Do …

     Writelog ("ending program..")

End sub


You can write more useful information , like the datetime of the log occur , current user that use this log..


IO.File.AppendAllText(logfile,mlog)


So you write as..


Io.file.appendalltext(logfile,string.concat(now , " " ,mlog))


You should have the log like this..


07-03-2011 6:35:01 PM starting program..
07-03-2011 6:35:02 PM doing stuff..
….
07-03-2011 6:36:01 PM ending program..

No comments:

Post a Comment