Solved

Custom logging in C#

Posted on 2007-11-16
11
864 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: 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!

 
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
 
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

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!

Question has a verified solution.

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

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

717 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