Solved

Custom logging in C#

Posted on 2007-11-16
11
859 Views
Last Modified: 2013-11-07
I am writing a window app (in C#) which reads an input xml file,parse it and updates SQLtables. This app runs once a day at night.I want to add logging (to a text file) to this app.

Could anyone explain to me how to go about doing this.

I want to create a separate log file everytime,so that logfiles can be archived.

Some examples would be very helpful.
0
Comment
Question by:Kiran_M
  • 5
  • 4
  • 2
11 Comments
 
LVL 16

Expert Comment

by:McExp
ID: 20300329
So to get this right, each time the app runs you want to generate a new log file (maybe with the datetime for a name) and output some text then close?
0
 
LVL 16

Expert Comment

by:McExp
ID: 20300396
You can call the function below whcich give a LogBase Location "c:\Logs" and a Message "Some" and it will create a new file (if required) and write a line to the end of the file with a date stamp at the start.

    private void logToFile(string LogBase, string LogMessage)
    {
        StreamWriter sw = new StreamWriter(string.Format(@"{0}\{1}.LOG", LogBase, DateTime.Now.ToString("yyyy-MM-dd")),true);
        sw.WriteLine(string.Format("{0}, {1}", LogMessage, DateTime.Now.ToString(@"yyyy\MM\dd HH:mm")));
    }
0
 

Author Comment

by:Kiran_M
ID: 20301758
Thank you. If i put the logToFile logic in a try/catch and Finally(close the logfile in it), that should take of care of closing the logfile properly, in case of Application termination (due to exceptions) right?

0
 
LVL 16

Expert Comment

by:McExp
ID: 20301800
Yes, apologies, the code ought to have been more robust, see below for a version which catches exceptions and cleans up after itself (with a using statment).

    private void logToFile(string LogBase, string LogMessage)
    {
        try
        {
            using (StreamWriter sw = new StreamWriter(string.Format(@"{0}\{1}.LOG", LogBase, DateTime.Now.ToString("yyyy-MM-dd")), true))
            {
                sw.WriteLine(string.Format("{0}, {1}", LogMessage, DateTime.Now.ToString(@"yyyy\MM\dd HH:mm")));
            }
        }
        catch
        {
            //Do we need to do something, or just ignore it?
        }
    }
0
 

Author Comment

by:Kiran_M
ID: 20322342
As you mentioned..using(streamWriter...)  is pretty neat  but it Creates,Write  and Close the streamwriter EVERYTIME i call logToFile method isn't it?  I want to Create/open the stream once at the top and call the log method  from different places in the code to write messages to log and close the stream at the end.

0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 16

Expert Comment

by:McExp
ID: 20323465
Ok, yea, the code i've suppled assumes that logging is quite infrequent. if you need to do this more I would probably change the single log function for a log class which in it's constructor opens/creates the log file, a method writes to the log file and another method or the destructor closes
0
 
LVL 11

Expert Comment

by:Mihai Stancescu
ID: 20327482
If you want to track only the errors from your application code, and from those methods that do not includes a try/catch statement you can use this:

in your Main() method in program.cs before Application.Run(); add this:




Hope this helps!
Regards,
Mishu
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

//done with Main()

/*

...

*/

//implementing Application_ThreadException

static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)

        {

            string msg = e.Exception.Message + Environment.NewLine + e.Exception.StackTrace;

            File.AppendAllText(@"C:\log.txt", msg);

        }

Open in new window

0
 

Author Comment

by:Kiran_M
ID: 20327685
Mishu, I need to log both informational and error messages to log file.
0
 
LVL 11

Expert Comment

by:Mihai Stancescu
ID: 20327700
Ok, I've covered the unhandled exception in my first post, and you can log all the info you need by using:
File.AppendAllText(@"C:\log.txt", msg); // msg is the string message you want to be logged.

Hope this helps!

Regards,
Mishu
0
 

Author Comment

by:Kiran_M
ID: 20327833
Thanks Mishu. File.AppendAllText  opens/write/close file  everytime I write to log is'nt it? i want to open and close only once in the application.
0
 
LVL 16

Accepted Solution

by:
McExp earned 125 total points
ID: 20336366
The following code should work for you.

--- Somewhere In your code ---
CSharpLogger csLogger = new CSharpLogger("C:\Temp\");
csLogger.WriteToLog("This is a message");
csLogger.Close();

--- CSharpLogger.cs ---
using System;
using System.IO;

public class CSharpLogger
{
    StreamWriter sw;

      public CSharpLogger(string LogBase)
      {
        sw = new StreamWriter(string.Format(@"{0}\{1}.LOG", LogBase, DateTime.Now.ToString("yyyy-MM-dd")), true);
      }

    public void WriteToLog(string LogMessage)
    {
        sw.WriteLine(string.Format("{0}, {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm"), LogMessage));
    }

    public void Close()
    {
        sw.Close();
        sw.Dispose();
    }
}
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Browsing the questions asked to the Experts of this forum, you will be amazed to see how many times people are headaching about monster regular expressions (regex) to select that specific part of some HTML or XML file they want to extract. The examp…
A short film showing how OnPage and Connectwise integration works.
This is a video that shows how the OnPage alerts system integrates into ConnectWise, how a trigger is set, how a page is sent via the trigger, and how the SENT, DELIVERED, READ & REPLIED receipts get entered into the internal tab of the ConnectWise …

919 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

20 Experts available now in Live!

Get 1:1 Help Now