附加到日志文件

时间:2018-02-12 22:23:06

标签: c#

我正在尝试将数据写入日志文件,但没有任何内容写入文件。 程序的目标是运行连续循环并继续查找文件,如果文件有效,则处理它并移动它。我正在记录任何错误和创建的项目。 此外,如何在循环运行时使我的日志文件可以访问,以便我可以看到附加了值。

   static void Main(string[] args)
    {
        var logFile = File.Create(filePath + "\\log_" + DateTime.Today.ToString("MMMM") + ".txt").ToString();

        while (true)
        {
            try
            {
                var moveTo = Directory.CreateDirectory(@"" + directoryPath + "Processed_" + DateTime.Today.ToString("MMMM"));
                var files = Directory.GetFiles(filePath);

                var todaysDate = DateTime.Now.Date;
                var firstOfMonth = new DateTime(todaysDate.Year, todaysDate.Month, 1);
                var monthEnd = firstOfMonth.AddMonths(1).AddDays(-1);

                if (todaysDate == monthEnd)
                {
                    File.Move(logFile, @"" + moveToNewPath + logFile);
                }

                foreach (var fileName in files)
                {
                    if (fileName.Contains("myFile.csv"))
                    {
                        var fileValues = File.ReadAllLines(filePath + fileName.Substring(44)).Skip(1).Select(v => new myFile(v)).ToList();

                        foreach (var i in fileValues)
                        {
                            try
                            {
                                var jsonValues = ValueFromFile(i);
                                var response = UploadData(url, username, password, values);
 this should be written to a log file ===> .File.AppendAllText(logFile, Environment.NewLine + DateTime.Now + "\t" + response); 
                            }
                            catch (Exception exception)
                            {
                                File.AppendAllText(logFile, Environment.NewLine + DateTime.Now + "\t" + exception.Message.Replace("\n", " "));
                            }
                        }

                        File.Move(fileName, @"" + directoryPath + "\\" + moveTo + "\\" + "processedMyFile" + DateTime.Now.Date.ToString("MM-dd-yy") + ".csv");
                    }
                }
            }

            catch (Exception exception)
            {
                File.AppendAllText(logFile, Environment.NewLine + DateTime.Now + "\t" + exception.Message.Replace("\n", " "));
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

让我们从程序顶部的这一行开始:

var logFile = File.Create(filePath + "\\log_" + DateTime.Today.ToString("MMMM") + ".txt").ToString();

我不确定你在ToString()电话挂断的情况下做了什么。它几乎肯定不会做你认为它做的事情。但我真的想在这里仔细研究documentation for the File.Create()方法。具体来说,这段摘录:

  

此方法创建的FileStream对象的默认FileShare值为None;在原始文件句柄关闭之前,没有其他进程或代码可以访问创建的文件。

哦,哦。这意味着稍后的File.AppendAllText()电话会失败。但是,让我们看一下AppendAllText() documentation.特别是这个:

  

如果文件不存在,该方法会创建该文件

意思是您可以删除顶部的问题行。你既不需要也不想要它。或者你可能只想在那里创建文件名,如下所示:

var logFile = Path.Combine(filePath, "log_" + DateTime.Today.ToString("MMMM") + ".txt");

作为奖励,我们正在探索更改此代码,以便将System.Diagnostics.TraceFileTraceListener结合使用,并且可能附加ConsoleTraceListener

static string moveToNewPath = "...";
static string filePath = "...";
static string logFormat = "\n{0:s}\t{1}";
static string logFile = "";
static string directoryPath = "...";

static void LogMessage(string FilePath, string Message)
{
    File.AppendAllText(Path.Combine(filePath, logFile),
         string.Format(logFormat, DateTime.Now, Message.Replace("\n", " ")));
}

static void Main(string[] args)
{
    logFile = "log_" + DateTime.Today.ToString("MMMM") + ".txt";

    //Rotate log file on last day of month
    try 
    {
        var todaysDate = DateTime.Now.Date;
        var firstOfMonth = new DateTime(todaysDate.Year, todaysDate.Month, 1);
        var monthEnd = firstOfMonth.AddMonths(1).AddDays(-1);
        if (todaysDate == monthEnd)
        {
            File.Move(Path.Combe(filePath, logFile), Path.Combine(moveToNewPath, logFile));
        }
    }
    catch (Exception ex)
    {
         LogMessage(ex.Message);
    }

    while (true)
    {
        // !!!!!!!!!!!!!!
        //Log rotate code used to be here... but... you need something to be sure this only happens once per day.
        // I STRONGLY suspect this code should be setup to run as 
        //   a SCHEDULED TASK set to run once per day or maybe once per hour, rather than an always-on background program.
        // !!!!!!!!!!!!!!!!
        try
        {
            var moveTo = Path.Combine(directoryPath, "Processed_" + DateTime.Today.ToString("MMMM"));
            Directory.CreateDirectory(moveTo);

            var files = Directory.GetFiles(filePath).Where(f => f.EndsWith("myFile.csv"));
            foreach (var fileName in files)
            {
                var fileValues = File.ReadAllLines(filePath + fileName.Substring(44)).Skip(1).Select(v => new myFile(v));

                foreach (var i in fileValues)
                {
                    try
                    {
                        var jsonValues = ValueFromFile(i);
                        var response = UploadData(url, username, password, jsonValues);
                        LogMessage(response); 
                    }
                    catch (Exception ex)
                    {
                        LogMessage(ex.Message); 
                    }
                }

                File.Move(fileName, Path.Combine(moveTo, "processedMyFile" + DateTime.Now.Date.ToString("MM-dd-yy") + ".csv"));
            }
        }

        catch (Exception ex)
        {
            LogMessage(ex.Message);
        }
    }
}