[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 890
  • Last Modified:

VB.NET CONSOLE APPLICATION- ADDING DEBIG SWITCH AND LOG FILES.

Hi,
I am working on VB.NET console application with a config file(app.config)

I have 2 questions :
 A) I want to create a log file at runt time, based on the path defined in the configuration file, to record all program activities like shown below.The file name must follow the naming standard so that we can purge them later using a scheduled script:

Example:
KRNUMBER_SAPSOURCESYTEM_TRANSPORTNUMBER.LOG.TXT

 
Example:
10:00:829 AM 8/9/2010 – Connecting to SAP server name..
10:01:321 AM 8/9/2010 – Successfully connected.
10:01:500 AM 8/9/2010 – Calling Z_BAPI_VALIDATE_TRANSPORT for KR# with parameters “CITK123456 CIT”

My current code for above Point a) is

 Public Sub WriteToLogFile(ByVal sLogFile As String, ByVal strError As String, ByVal intKRNUMBER As Integer, ByVal strSAPSOURCESYTEM As String, ByVal intTRANSPORTNUMBER As Integer, ByVal strMessage As String)

        Dim filename As New StringBuilder
        filename.Append(intKRNUMBER)
        filename.Append("_")
        filename.Append(strSAPSOURCESYTEM)
        filename.Append("_")
        filename.Append(intTRANSPORTNUMBER)
        filename.Append(".LOG")

        Dim fullpath As String = sLogFile + filename.ToString()

        Dim fs As FileStream = Nothing
        If File.Exists(fullpath) Then
            fs = New FileStream(fullpath, FileMode.Append, FileAccess.Write)
        Else

            fs = New FileStream(fullpath, FileMode.OpenOrCreate, FileAccess.Write)
        End If


        Dim fsWriter As StreamWriter = Nothing

        fsWriter = New StreamWriter(fs)
        fsWriter.WriteLine(Format(Date.Now, "HH:MM:ss tt MM/dd/yyyy") + " - " + strMessage)

        fsWriter.Flush()
        fsWriter.Close()
        fsWriter.Dispose()
        fs.Flush()
        fs.Close()
        fs.Dispose()

        'Create a log file, based on the path defined in the configuration file, to record all program activities related to the Transport.

        'Example:
        '10:00:829 AM 8/9/2010 – Connecting to SAP server name..
        '10:01:321 AM 8/9/2010 – Successfully connected.
        '10:01:500 AM 8/9/2010 – Calling Z_BAPI_VALIDATE_TRANSPORT for KR# with parameters “CITK123456 CIT”

        'The file name must follow the naming standard so that we can purge them later using a scheduled script:
        'KRNUMBER_SAPSOURCESYTEM_TRANSPORTNUMBER.LOG.TXT

    End Sub

PLEASE PROVIDE A BETTER WAY SO THAT I CAN LOG EACH /ALL ACTIVITIS OF PROGRAM AT RUN TIME INCLUDING ERRORS IN LOG FILE.

 B) Similarly, I want to add Add the debug switch in the Configuration file to indicate whether the program is debug mode or production mode. Modify code to execute based on this setting; if Debug is set to true then do not call the BAPI but record all activities as if it is calling the BAPI. Print the value of this switch in the console and the log file.

 PLEASE PROVIDE CODE ASAP FOR BOTH POINT A) AND PONIT B). SEND ME MAIL IN CASE OF ANY CONFUSION OR CALL ME AT +919535194027


Thanks & Regads,
Deepak
KR.DEEPAK123@GMAIL.COM
+919535194027
0
krdeepak123
Asked:
krdeepak123
  • 7
  • 3
  • 2
  • +1
1 Solution
 
krdeepak123Author Commented:
Points are increased...
0
 
Éric MoreauSenior .Net ConsultantCommented:
0
 
Alpesh PatelAssistant ConsultantCommented:
Hi,

You can use System.Diagnostic's LogEntry Method to save log at specified file.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
angus_young_acdcCommented:
You could use something as simple as a StreamWriter and log out that way.  Or, and this would be my recommended choice, use Log4Net.  You can log out to several different formats, set the debug mode and keep your log file name in a config file.  For example add a reference to log4net, then in your app.config file:
<?xml version="1.0" encoding="utf-8" ?>

 
   
     
   
 
 
 
 
 
 

   
     
     
     
     
     
     
     
     
       
     
   
   
     
     
   
   
     
   
 
 
   
 


This will write out every instance that you're put in to be logged, you can change the priority to log warnings or errors.

Then in your app put this as a global variable:
log4net.ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

And then this when your app starts:
XmlConfigurator.Configure();

Then from here all you have to do is log.Debug("Message), log.Warn("message"), log.Error("message") etc where you would like to log something out
0
 
krdeepak123Author Commented:
Hi emreau,

Your technique of tracing enables to write into log file our own sentences(i.e. strings say "hi") only when we call Writeline method but this complete technique does not serve the purpose if i want to record all activities of the program during run time and not a strign liek "hi".

E.G. If i want to record each and every thing during run time as what and how program(this console app) make connection to other program.(please see below)

10:00:829 AM 8/9/2010 – Connecting to SAP server name..
10:01:321 AM 8/9/2010 – Successfully connected.
10:01:500 AM 8/9/2010 – Calling Z_BAPI_VALIDATE_TRANSPORT for KR# with parameters “CITK123456 CIT”

etc.

Is there any thing/tool/technique to do it.Above technique using Trace.writelineif(..) looks to ms as Response.write("..")  in asp.net with condtion and does not serve purpose to write into file based on switch values e.g. if i change trace switch value from 0->1in this console application's app.config  then the application should record only errors or 0->3 then it shoudl recorrd only information etc.

Please comment.

Thanks & Regards,
Deepak
0
 
krdeepak123Author Commented:
Hi angus_young_acdc,

Will your technique of using log4net will track all the things of runtime in program i.e.

10:00:829 AM 8/9/2010 – Connecting to SAP server name..
10:01:321 AM 8/9/2010 – Successfully connected.
10:01:500 AM 8/9/2010 – Calling Z_BAPI_VALIDATE_TRANSPORT for KR# with parameters “CITK123456 CIT”

and is it possible that by changing the value of switch , i can track whatver i want like errors only ,information only etc.?

This log4net is MS Tool or apache tool? Also in your above comment, the app.config file is not having correct syntax it seems as i coopied the contents into xml file and that cml file showing some syntax errors in browser.


Thanks & Regards,
Deepak
kr.deepak123@gmail.com
+919535194027
0
 
krdeepak123Author Commented:
Hi All,

The requirment is shown below FOR MORE CLARIFICATION TO YOU GUYS which shows tha run time program activities needs to be tracked INSTEAD printing any kind of string like "hi" or "hello"....Let me know your comments.

1) Log Files
Create a log file, based on the path defined in the configuration file, to record all program activities related to the Transport.

Example:
10:00:829 AM 8/9/2010 – Connecting to SAP server name..
10:01:321 AM 8/9/2010 – Successfully connected.
10:01:500 AM 8/9/2010 – Calling Z_BAPI_VALIDATE_TRANSPORT for KR# with parameters “CITK123456 CIT”

The file name must follow the naming standard so that we can purge them later using a scheduled script:

Example:
KRNUMBER_SAPSOURCESYTEM_TRANSPORTNUMBER.LOG.TXT

2)  Debug Switch
Add the debug switch in the Configuration file to indicate whether the program is debug mode or production mode. Modify code to execute based on this setting; if Debug is set to true then do not call the BAPI but record all activities as if it is calling the BAPI. Print the value of this switch in the console and the log file.

Thanks & Regards,
Deepak
kr.deepak123@gmail.com
+919535194027
0
 
krdeepak123Author Commented:
Also just for your refrence, this program is VB.NET CONSOLE APPLICATION.

Thanks & Regards,
Deepak
kr.deepak123@gmail.com
+919535194027
0
 
Éric MoreauSenior .Net ConsultantCommented:
I think you have everything in my article:
>>if i change trace switch value from 0->1in this console application's app.config  then the application should record only errors or 0->3 then it shoudl recorrd only information
check my article tor the TraceSwitch usage like : Trace.WriteLineIf(mTS.TraceError, "Written when the switch is set to Error (or greater).")
The trick is the If in WriteLineIf.

>>if Debug is set to true then do not call the BAPI but record all activities as if it is calling the BAPI.
this is a bit different. You can use the BooleanSwitch maybe.
 

if mBS.Enabled then
   'do your real stuff
else
   trace.writeline("fake call")
end if

Open in new window

0
 
krdeepak123Author Commented:
Hi emoreau,

This is fine that we can change switch value in app.config and then using runtime code say Trace.Writelineif(true or false, "hi") but i dont want to print "hi"..instaed i want to print what the program is doing during run time say it is connecting to server or not and if could not make connection then what is error.  I mean to say that using your technique i can write Trace.Writelineif(traceswitch.Info,"connection successful" ) but again this is strign written by me as developer ...in case i want to trace the actual information of program and tarck errors during connection then what should be  technique.

For me this technquie of tarcing seems printing some string that too written by developer based on switch value but how to catch what progarm is doing internally and how to catch real time erros in real time and print that.

like --connection sucessfull, could not connect,502 error etc. in trace file or log file
Thanks & Regards,
Deepak
kr.deepak123@gmail.com
+919535194027
0
 
angus_young_acdcCommented:
Hi krdeepak123

You will be able to log whatever you want, so for example:
log.Debug("Connecting to SAP server name..");  // Log4net outputs the date & time

And yes, if you change the config priority you can have it record whatever you wish, so if you select error then it will only output errors.

It's a 3rd party DLL for .Net languages (free by the way!).

Yeah I would image that there would be teething issues with the config, as I just ripped it from one of my apps and took out the sensitive material. I've attached a new copy.

In response to your below statement about wanting somethign that logs out what the app is doing, as far as I'm aware you will have to tell it (no matter what you go for) exactly what to print out.  All code is logical (supposidly :-) ) and won't just do things on a whim, you need to tell the app what to do.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<configSections>
		<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, &#xD;&#xA;    log4net"/>
		<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    </sectionGroup>
	</configSections>
	<connectionStrings>
  </connectionStrings>
	<appSettings>
  </appSettings>
	<log4net debug="false">
		<appender name="LogFileAppender" type="log4net.Appender.FileAppender,log4net">
			<param name="File" value="ErrorLog.txt"/>
			<param name="AppendToFile" value="true"/>
			<param name="MaxSizeRollBackups" value="9"/>
			<param name="MaximumFileSize" value="1"/>
			<param name="RollingStyle" value="Size"/>
			<param name="StaticLogFileName" value="true"/>
			<param name="requirePermission" value="false"/>
			<layout type="log4net.Layout.PatternLayout,log4net">
				<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] &lt;%X{auth}&gt; - %m%n"/>
			</layout>
		</appender>
		<root>
			<priority value="ALL"/>
			<appender-ref ref="LogFileAppender"/>
		</root>
		<category name="YourApp">
			<priority value="ALL"/>
		</category>
	</log4net>
	<applicationSettings>
    
  </applicationSettings>
</configuration>

Open in new window

0
 
Éric MoreauSenior .Net ConsultantCommented:
>>For me this technquie of tarcing seems printing some string that too written by developer based on switch value but how to catch what progarm is doing internally and how to catch real time erros in real time and print that.

I do not know application that can report what it is doing without the programmer providing this information.
0
 
krdeepak123Author Commented:
Thanks emoreau.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 7
  • 3
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now