Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Custom logging in C#

Posted on 2007-11-16
11
Medium Priority
?
868 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Screencast - Getting to Know the Pipeline
Suggested Courses
Course of the Month20 days, 19 hours left to enroll

810 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