1

Hi Sorry If this is a foolish one.

I have created a Logger class where it logs information and I am using Logger class in different projects and logging information. I have a requirement where I need to send an email attachment of the log file after finished writing.

But filepath location is in Logger.cs class how can I know the location of the file in the project I am using logger.

** Logger.cs **

public  class Logger
{

    // logFilePath where to write?
    readonly string logFilePath = string.Empty;

    /// <summary>
    /// Constructor
    /// </summary>
    public  Logger()
    {
        String filePath = string.Format("{0:yyyy-MM-dd}", DateTime.Now);

        // This is the text file created with time stamps
        var folderName = ConfigurationManager.AppSettings["FolderToCreate"];
        String txtFile = string.Format("Log{0:yyyy-MM-dd hh-mm-ss-tt}", DateTime.Now);
        // Given in config to read the path 
        var localhostizedLetter = ConfigurationManager.AppSettings["localhostDriveLetter"]+"//";
        //Create directory
        string pathString = Path.Combine(localhostizedLetter, folderName);
        if (!Directory.Exists(pathString))
        {
            Directory.CreateDirectory(pathString);
        }
        // Create a folder inside directory 
        // If folder exists dont create it 
        pathString = Path.Combine(pathString, filePath);
        if (!Directory.Exists(pathString))
        {
            Directory.CreateDirectory(pathString);
        }
        // create a file inside d://DataSummarisationDatetime.now//datetimewithtimestamp.txt
        // if exists please dont create it.
        pathString = Path.Combine(pathString, txtFile);
        if (!Directory.Exists(pathString))
        {
            // here my file is created and opened.
            // so I m doing a try catch to make sure if file is opened we are closing it so that nother process can use it
            File.Create(pathString).Dispose();
            var fileInfo = new FileInfo(pathString);
            IsFileLocked(fileInfo);

        }
        logFilePath = pathString;

        //logFilePath = ConfigurationManager.AppSettings["localhostDriveLetter"] + "\\" + "RetailerfeedLogFiles" + "\\" + string.Format("RetailerFeed{0:yyyy-MM-dd hh-mm-ss-tt}", DateTime.Now) + ".txt";
    }

    /// <summary>
    ///  To check if File is opened by another process.
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    private bool IsFileLocked(FileInfo file)
    {
        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            //the file is unavailable because it is:
            //still being written to
            //or being processed by another thread
            //or does not exist (has already been processed)
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        //file is not locked
        return false;
    }

    /// <summary>
    /// Log message using textwriter
    /// </summary>
    /// <param name="logMessage"></param>
    /// <param name="w"></param>
    public static void Log(string logMessage, TextWriter w)
    {
        w.Write("\r\n" + DateTime.Now + " " + logMessage);
        w.Flush();
    }

    /// <summary>
    /// Call this function to log your message
    /// </summary>
    /// <param name="textLog"></param>
    public void Log(string textLog)
    {
        StreamWriter sw = null;

        if (!File.Exists(logFilePath))
        {
            try
            {
                sw = File.CreateText(logFilePath);
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                sw.Dispose();
            }

        }
        try
        {

            using (StreamWriter w = File.AppendText(logFilePath))
            {
                Log(textLog, w);

                w.Close();
            }

        }
        catch (Exception exception)
        {

            throw exception;
        }

    }

}

** RetailerFeed.cs **

public partial class RetailerFeeds : Form
{
  private Logger _logger = new Logger();
    _logger.Log("                                ");
            _logger.Log(" Total no.of scrapes/retailers  to Process    :  " + scrapesRun.Count());
            _logger.Log(" Starting RetailerFeeds Processing " );
            _logger.Log("       ");
            _logger.Log(" Processing : " + scrape.Retailer.Description);

_keepItDry.SendRetailerFeedNotification("Ended RetailerFeeds Interface " , stringBuilder.ToString());


}
  • SendRetailerFeedNotification I need to send logfile as an attachment *
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82
Achieve Solution
  • 190
  • 1
  • 11
  • Expose the file name as a public property. Also, dont use `throw exception;`, use `throw;` - http://stackoverflow.com/questions/178456/what-is-the-proper-way-to-re-throw-an-exception-in-c. – Kami Oct 17 '13 at 13:53

2 Answers2

1

Simply change

readonly string logFilePath = ... ;

to

public string LogFilePath { get; set; }

and its value will be available to other code.

Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
0

You just need to change your Logger class to expose the Filepath somehow.

  • as public variable,
  • as public property,
  • with a public Function returning the Filepath

then you will have Access to it in your Main Program

BigM
  • 678
  • 1
  • 17
  • 28