我编写了一个C#程序,它使用下面的logFile进行记录。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="logFile" value="D:\logs\MyProgramLog.txt"/>
</appSettings>
</configuration>
static class LoggingClass
{
public static void info(string messString)
{
try
{
//show log on console
Console.WriteLine(messString);
//write log to log file
using (StreamWriter sw = new StreamWriter(ConfigurationManager.AppSettings["logFile"].ToString(), true))
{
sw.WriteLine("info: " + messString);
}
}
catch (Exception ex)
{
}
}
}
static void Main(string[] args)
{
LoggingClass.info("Started Program run at" +DateTime.Now);
}
每次日志文件名都是MyProgramLog.txt。 如何动态地将logFile名称更改为MyProgramLog_2015_02_13.txt,即将日期附加到app.config文件中的日志文件名称?
答案 0 :(得分:0)
这是您要查找的代码:
var path = Path.GetDirectoryName(logFile);
var fileName = Path.GetFileNameWithoutExtension(configFile);
var todayFileName = fileName + DateTime.Now.ToString("_yyyy_MM_dd");
var ext = Path.GetExtension(configFile);
var newLogFile = path + todayFileName + ext;