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
Solved

Custom logging in C#

Posted on 2007-11-16
11
861 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
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

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

860 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