1

こんにちは、これがばかげている場合は申し訳ありません。

情報をログに記録する Logger クラスを作成し、さまざまなプロジェクトで Logger クラスを使用して情報を記録しています。書き込み終了後にログ ファイルの添付ファイルを電子メールで送信する必要があるという要件があります。

しかし、ファイルパスの場所は Logger.cs クラスにあります。ロガーを使用しているプロジェクト内のファイルの場所を知るにはどうすればよいですか。

** 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 ログファイルを添付ファイルとして送信する必要があります *
4

2 に答える 2

1

変更するだけ

readonly string logFilePath = ... ;

public string LogFilePath { get; set; }

その値は他のコードで使用できます。

于 2013-10-17T13:54:55.943 に答える
0

Logger クラスを変更して Filepath を何らかの形で公開するだけです。

  • パブリック変数として、
  • 公共の財産として、
  • Filepath を返す public Function を使用

その後、メインプログラムでアクセスできます

于 2013-10-17T14:14:36.077 に答える