none
C# write to log file

    Question

  •  In an existing C# 2008 application, I want to have error messages written to a log file that can be saved and looked at later for a reference. I basically want to generate console.writeline messages and save the output. I could also use something like objUtil.LogMessage to accomplish this goal.

     I would like to accomplish the following goals:

    1. Do I need to 'open' some kind of a log file. If so, how would you code this?
    2. I would like to save ex.messages that are located in try catch blocks. Does this require any special code?
    3. I would like to open and save the log files to a certain directory path location.

    4. I could possibly use objUtil.LogMessage and/or console.writeline separate or together? Is this possbile, if so how is this possible?

    Thus can you tell me and or show me in code how to accomplish any and/or all of the goals I just listed above?



    Friday, November 09, 2012 4:54 PM

Answers

  • 1. http://www.itauthor.com/2007/08/21/writing-to-a-log-file-in-c/

    2. You can just use string variable and parse the exception message into that variable. After that you can store that variable into a log file

    3. If you are doing this via GUI than create textbox control just for writting the path. Also you can look at this http://www.dotnetperls.com/openfiledialog or if you are doing with Console apps you can just create menus (while -> if) which will provide you a full path to where you want to save your log file. Use your imagination :)

    4. Console.WriteLine() is method which provides output in the console. There is no way that you can store something into a log file with that method. You can only use that method to be 100% sure if that log file is saved or if it is already existing. 

    Friday, November 09, 2012 9:05 PM
  • One option is to use System.Diagnostics.Debug.WriteLine methods.  Then you can turn on or off log capture through your application configuration file by defining a trace listener.    This is really easy to do for console and WPF and WinForms applications.   You can specific where the log files are saved and how much information to log.

    Capturing System.Diagnostics.Debug.WriteLine output in an ASP.NET environment is not as easy so easy. 

    Also, Enterprise Library contains some application blocks for adding custom logging, including for application exceptions.  

    If you still prefer your own logging mechanism, I can post a quick example for you.

    Matt

    Friday, November 09, 2012 5:49 PM

All replies

  • One option is to use System.Diagnostics.Debug.WriteLine methods.  Then you can turn on or off log capture through your application configuration file by defining a trace listener.    This is really easy to do for console and WPF and WinForms applications.   You can specific where the log files are saved and how much information to log.

    Capturing System.Diagnostics.Debug.WriteLine output in an ASP.NET environment is not as easy so easy. 

    Also, Enterprise Library contains some application blocks for adding custom logging, including for application exceptions.  

    If you still prefer your own logging mechanism, I can post a quick example for you.

    Matt

    Friday, November 09, 2012 5:49 PM
  • 1. http://www.itauthor.com/2007/08/21/writing-to-a-log-file-in-c/

    2. You can just use string variable and parse the exception message into that variable. After that you can store that variable into a log file

    3. If you are doing this via GUI than create textbox control just for writting the path. Also you can look at this http://www.dotnetperls.com/openfiledialog or if you are doing with Console apps you can just create menus (while -> if) which will provide you a full path to where you want to save your log file. Use your imagination :)

    4. Console.WriteLine() is method which provides output in the console. There is no way that you can store something into a log file with that method. You can only use that method to be 100% sure if that log file is saved or if it is already existing. 

    Friday, November 09, 2012 9:05 PM
  • Hi Wendy,

    You probably already have your answer, but I just saw your post and thought you might be interested in my own solution.  I created a .cs file called LogFile.cs within my project.  This is what it contains...

    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    namespace CodedUIDataAccess
    {
      public class LogFile
      {
        private string fileName;
        public LogFile()
        {
          fileName = "C:\\TestLogData\\AUT Test Results.txt";
        }
        public LogFile(string fileName)
        {
          this.fileName = fileName;
        }
        ////Use LogFile to document the test run results
        /// <summary>
        /// The MyLogFile method is used to document details of each test run.
        /// </summary>
        public void MyLogFile(string strCategory, string strMessage)
        {
          // Store the script names and test results in a output text file.
          using (StreamWriter writer = new StreamWriter(new FileStream(fileName, FileMode.Append)))
          {
            writer.WriteLine("{0}{1}", strCategory, strMessage);
          }
        }
      }
    }

    All of the other .cs files in my project reference this file, so logged messages can be made anywhere within the code...

    // In each .cs file, add the logger namespace...
    using CodedUIDataAccess;

    The first statement within the main Class of each .cs file instantiates the Method...

    // At the beginning of the main Class in each .cs file, reference the MyLogFile method...
    LogFile logger = new LogFile();

    Here's an example of using the log file to capture an exception...

    catch (Exception e)
    {
      logger.MyLogFile("    *** FAILED Action:  '" + key.ActionName, "' error '" + e.Message + "'");
      throw new PlaybackFailureException("  Step " + stepNumber + " ACTION: '" + key.ActionName + "' error '" + e.Message + "'");
    }
    Basically, you're just passing 2 strings into the MyLogFile method.  I use the first to identify the category of the failure (i.e., Data Entry, Verification, Action, etc.) and the second to log a specific message.  In this case, it's just repeating what exception was identified.  Hope this helps.


    Kevin

    Monday, November 19, 2012 3:49 PM