简体   繁体   English

将日志写入日志文件后,将该文件作为电子邮件附件发送

[英]After writing log to Log file send that file as attachment to email

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. 我创建了一个Logger类,用于记录信息,并且在不同的项目和日志记录信息中使用Logger类。 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类中,我如何知道我在使用记录器的项目中文件的位置。

** 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 ** ** 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 * SendRetailerFeedNotification我需要将日志文件作为附件发送*

Simply change 只需更改

readonly string logFilePath = ... ;

to

public string LogFilePath { get; set; }

and its value will be available to other code. 其值将可用于其他代码。

You just need to change your Logger class to expose the Filepath somehow. 您只需要更改Logger类以某种方式公开Filepath。

  • as public variable, 作为公共变量,
  • as public property, 作为公共财产,
  • with a public Function returning the Filepath 与一个公共函数返回文件路径

then you will have Access to it in your Main Program 那么您将可以在主程序中访问它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM