开发者

StreamWriter not updating its path on new day

开发者 https://www.devze.com 2023-03-13 17:40 出处:网络
I have a program that\'s writing to a log file called \"appname_yyyyMMdd.log\", where appname is the name of my app, and yyyyMMdd is the current date; a sample log file name might be \"loglistener_201

I have a program that's writing to a log file called "appname_yyyyMMdd.log", where appname is the name of my app, and yyyyMMdd is the current date; a sample log file name might be "loglistener_20110615.log" . Anyway, my app creates the log file fine, and it updates it as planned. However, once the date changes, the app doesn't log anything, and it doesn't create a new file. In other words, since today is 6/15, I need it to create a file called "loglistener_20110616.log" after midnight tonight, and I need it to continue logging to that new file.

Here are code excerpts:

public static void LogInfo(string format, params object[] args)
{
    lock (_logLock)
    {
        using (StreamWriter sw = File.AppendText(GetLogPath()))
        {
            sw.WriteLine(GetTimeStamp() + String.Format(format, args));
        }
    }
}

private static string GetLogPath()
{
    string appName = "loglistener";
    string today = DateTime.Today.ToString("yyyyMMdd");
    string fileName = appName + "_" + today + ".log";
    string fullLogPath = AppDomain.CurrentDomain.Bas开发者_如何学运维eDirectory + fileName;

    return fullLogPath;
}

I checked this similar question, but that question describes a different scenario (with a non-applicable fix).

UPDATE - Just in case googlers land on this page, I later discovered a different cause altogether w/ this. My log is logging info from an email-listening service. The service itself had a problem where it was timing out after a half-hour. So, my problem wasn't w/ CreateText / AppendText... My problem was there was nothing to log. Very annoying, but I hope other people won't be misled by this question/answer.


You should check to make sure that the file exists first.

From the File.AppendText Documentation

Type: System.IO.StreamWriter A StreamWriter that appends UTF-8 encoded text to an existing file.

public static void LogInfo(string format, params object[] args)
{
    lock (_logLock)
    {
        using (StreamWriter sw = File.Exists(GetLogPath) ? File.AppendText(GetLogPath()) : File.CreateText(GetLogPath())
        {
            sw.WriteLine(GetTimeStamp() + String.Format(format, args));
        }
    }

}

Try that instead

After looking at the comments and re-reading the documentation.

File.AppendText

Should always work, regardless of file existence.

0

精彩评论

暂无评论...
验证码 换一张
取 消