Solved

Custom logging in C#

Posted on 2007-11-16
11
858 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

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

Join & Write a Comment

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…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

706 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