Solved

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

Posted on 2010-11-10
13
846 Views
Last Modified: 2012-08-13
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
Comment
Question by:krdeepak123
  • 7
  • 3
  • 2
  • +1
13 Comments
 

Author Comment

by:krdeepak123
ID: 34100698
Points are increased...
0
 
LVL 69

Accepted Solution

by:
Éric Moreau earned 150 total points
ID: 34100713
0
 
LVL 21

Expert Comment

by:Alpesh Patel
ID: 34101533
Hi,

You can use System.Diagnostic's LogEntry Method to save log at specified file.
0
 
LVL 15

Expert Comment

by:angus_young_acdc
ID: 34101706
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
 

Author Comment

by:krdeepak123
ID: 34109687
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
 

Author Comment

by:krdeepak123
ID: 34109735
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:krdeepak123
ID: 34110051
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
 

Author Comment

by:krdeepak123
ID: 34110056
Also just for your refrence, this program is VB.NET CONSOLE APPLICATION.

Thanks & Regards,
Deepak
kr.deepak123@gmail.com
+919535194027
0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 34110274
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
 

Author Comment

by:krdeepak123
ID: 34110482
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
 
LVL 15

Expert Comment

by:angus_young_acdc
ID: 34113803
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
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 34113970
>>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
 

Author Closing Comment

by:krdeepak123
ID: 34134346
Thanks emoreau.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
How to trouble shoot .net contact form 3 30
Need help with a query 6 54
System32Int Error 8 44
Limiting string to two deciamls 18 30
I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now