C# 每天创建一个新的日志文件
正如标题所暗示的那样,如何在C#中每天创建一个新的日志文件?现在,该程序可能不一定要昼夜运行,而只能在工作时间调用。所以我需要做两件事C# 每天创建一个新的日志文件,c#,asp.net,winforms,logging,log4net,C#,Asp.net,Winforms,Logging,Log4net,正如标题所暗示的那样,如何在C#中每天创建一个新的日志文件?现在,该程序可能不一定要昼夜运行,而只能在工作时间调用。所以我需要做两件事 如何每天创建一个新的日志文件?日志文件的名称格式为MMDDYYYY.txt 我怎样才能在午夜之后创建它,以防它运行到整晚 你不需要在特定的时间创建它-在最简单的情况下,你可以在启动应用程序的日志服务时检查是否有以今天的日期为名称的日志文件,如果没有,你可以在开始附加到它之前创建一个日志文件 使用此设置,您需要特别注意的唯一情况是应用程序运行到午夜之后 使用。这是
你不需要在特定的时间创建它-在最简单的情况下,你可以在启动应用程序的日志服务时检查是否有以今天的日期为名称的日志文件,如果没有,你可以在开始附加到它之前创建一个日志文件 使用此设置,您需要特别注意的唯一情况是应用程序运行到午夜之后 使用。这是最常用的日志库之一
它可以根据您的喜好轻松配置,请参考示例。当您记录某些内容时,请检查是否存在具有当前日期的文件,如果不存在,请创建它。就这么简单:)
在需要之前无需创建,请使用:
file = new StreamWriter(path, true, new UTF8Encoding(false));
(或者可能是另一种编码。)如果该文件不存在,则会创建该文件,或者开始附加到该文件
然后就是创建文件名,然后使用它。我建议这样做:
string logFile = DateTime.Now.ToString("yyyyMMdd") + ".txt";
if (!System.IO.File.Exists(logFile))
{
System.IO.File.Create(logFile);
}
//append to logFile here...
你有什么理由想在午夜后创作它吗?如果在记录错误时它不存在,为什么不创建它呢
还注意到我更改了日期格式。这将允许您按名称对文件进行排序,并使其按顺序排列。我总是在以任何方式处理日期时使用这种格式。2018年更新:我现在更喜欢使用NLog 关于log4net的上一个答案: 显示如何配置RollingFileAppender以在日期期间滚动日志文件。此示例将每分钟滚动一次日志文件!要更改滚动周期,请调整DatePattern值。例如,“yyyyMMdd”的日期模式将每天滚动。
有关可用模式的列表,请参见
尝试NLog()。在我看来,它比Log4Net更灵活、更容易使用
示例NLog.config:
<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="file" xsi:type="File"
layout="${longdate} ${logger} ${message}"
fileName="${basedir}/${shortdate}/${windows-identity:domain=false}.${level}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file" />
</rules>
</nlog>
有关更多示例(包括除文件之外的其他日志记录目标),请参见其他人提到了Log4Net,因此我将继续介绍日志记录块,它也可以做您想要的事情
你能提供一些代码来说明每天制作这个卷有多容易吗?它比log4Net示例更简单吗?-丹尼尔·戴森 当然。通常,人们会使用它来构建配置;这个工具需要一点时间来适应,但一旦你了解了它的工作原理,它就相当强大了。也就是说,您还可以手动编辑
app.config
这是我提到的工具的输出,它将几乎所有内容转储到每天滚动的平面文件中(或者如果超过2MB)。格式设置是该工具提供的默认设置
下面是我当前使用的appender XML 根据您对
1) 每天创建一次日志文件,
2) 要拥有txt的扩展名,
您应该使用与下面类似的XML。
下面的XML将创建一个名为system-20121106.txt的日志文件 唯一的问题是,由于文件值是logs/system,所以当您的文件为当天写入时,它将是system-。要解决这个问题,您必须将文件值设置为logs/system.txt,然后将system.txt.20121106.txt作为最终文件
如果您只需要一个简单的
TraceListener
,我这里有一个小型实现:
输出也是CSV格式,因此您可以使用Excel或任何CSV阅读器读取
TraceListener的源代码
:
public class DailyTraceListener : TraceListener
{
public bool UseUtcTime { get; private set; }
public string LogFolder { get; private set; }
public bool Disposed { get; private set; }
public bool HasHeader { get; private set; }
public string CurrentLogFilePath { get; private set; }
protected DateTime? CurrentLogDate { get; set; }
protected FileStream LogFileStream { get; set; }
protected StreamWriter LogFileWriter { get; set; }
private SemaphoreSlim LogLocker { get; set; } = new SemaphoreSlim(1, 1);
public DailyTraceListener(string logFolder)
{
this.LogFolder = logFolder;
}
public DailyTraceListener UseUtc()
{
this.UseUtcTime = true;
return this;
}
public DailyTraceListener UseHeader()
{
this.HasHeader = true;
return this;
}
protected virtual void WriteHeader()
{
this.LogFileWriter.WriteLine(string.Format("{0},{1},{2},{3},{4}",
"Time",
"Type",
"Source",
"ID",
"Message"));
}
protected virtual string FormatTime(DateTime time)
{
return time.ToString("o");
}
private DateTime GetCurrentTime()
{
if (this.UseUtcTime)
{
return DateTime.UtcNow;
}
else
{
return DateTime.Now;
}
}
private void InitializeLogFile()
{
this.CheckDisposed();
try
{
if (this.LogFileWriter != null)
{
this.LogFileWriter.Dispose();
}
if (this.LogFileStream != null)
{
this.LogFileWriter.Dispose();
}
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
var currentTime = this.GetCurrentTime();
var fileName = $"{currentTime.ToString("yyyy-MM-dd")}.log";
this.CurrentLogFilePath = Path.Combine(this.LogFolder, fileName);
// Ensure the folder is there
Directory.CreateDirectory(this.LogFolder);
// Create/Open log file
this.LogFileStream = new FileStream(this.CurrentLogFilePath, FileMode.Append);
this.LogFileWriter = new StreamWriter(this.LogFileStream);
// Write Header if needed
if (this.LogFileStream.Length == 0 && this.HasHeader)
{
this.WriteHeader();
}
}
private void CheckFile()
{
this.CheckDisposed();
var currentTime = this.GetCurrentTime();
if (this.CurrentLogDate == null || currentTime.Date != this.CurrentLogDate)
{
this.InitializeLogFile();
this.CurrentLogDate = currentTime.Date;
}
}
private void CheckDisposed()
{
if (this.Disposed)
{
throw new InvalidOperationException("The Trace Listener is Disposed.");
}
}
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
{
var time = this.FormatTime(this.GetCurrentTime());
this.WriteLine(string.Format("{0},{1},{2},{3},{4}",
time,
eventType,
EscapeCsv(source),
id.ToString(),
EscapeCsv(message)));
}
public override void Write(string message)
{
try
{
this.LogLocker.Wait();
this.CheckDisposed();
this.CheckFile();
var currentTime = this.GetCurrentTime();
this.LogFileWriter.Write(message);
this.LogFileWriter.Flush();
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
finally
{
this.LogLocker.Release();
}
}
public override void WriteLine(string message)
{
this.Write(message + Environment.NewLine);
}
protected string EscapeCsv(string input)
{
for (int i = 0; i < input.Length; i++)
{
if (input[i] == ',' || input[i] == '\n')
{
input = input.Replace("\"", "\"\"");
return $"\"{input}\"";
}
}
return input;
}
protected override void Dispose(bool disposing)
{
this.Disposed = true;
try
{
this.LogFileWriter?.Dispose();
this.LogFileStream?.Dispose();
this.LogLocker.Dispose();
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
base.Dispose(disposing);
}
}
公共类DailyTraceListener:TraceListener
{
公共布尔使用时间{get;私有集;}
公用字符串日志文件夹{get;private set;}
public bool Disposed{get;private set;}
公共布尔哈希头{get;private set;}
公共字符串CurrentLogFilePath{get;private set;}
受保护的日期时间?CurrentLogDate{get;set;}
受保护的文件流日志文件流{get;set;}
受保护的StreamWriter LogFileWriter{get;set;}
私有信号量lim LogLocker{get;set;}=新信号量lim(1,1);
公共DailyTraceListener(字符串日志文件夹)
{
this.LogFolder=LogFolder;
}
公共DailyTraceListener UseUtc()
{
this.UseUtcTime=true;
归还这个;
}
公共DailyTraceListener UseHeader()
{
this.HasHeader=true;
归还这个;
}
受保护的虚拟void WriteHeader()
{
this.LogFileWriter.WriteLine(string.Format(“{0},{1},{2},{3},{4}”),
“时间”,
“类型”,
“来源”,
“身份证”,
"讯息");;
}
受保护的虚拟字符串FormatTime(日期时间)
{
返回时间。ToString(“o”);
}
私有日期时间GetCurrentTime()
{
if(this.useutcime)
{
return DateTime.UtcNow;
}
其他的
{
返回日期时间。现在;
}
}
private void InitializeLogFile()
{
这个;
尝试
{
如果(this.LogFileWr
public class DailyTraceListener : TraceListener
{
public bool UseUtcTime { get; private set; }
public string LogFolder { get; private set; }
public bool Disposed { get; private set; }
public bool HasHeader { get; private set; }
public string CurrentLogFilePath { get; private set; }
protected DateTime? CurrentLogDate { get; set; }
protected FileStream LogFileStream { get; set; }
protected StreamWriter LogFileWriter { get; set; }
private SemaphoreSlim LogLocker { get; set; } = new SemaphoreSlim(1, 1);
public DailyTraceListener(string logFolder)
{
this.LogFolder = logFolder;
}
public DailyTraceListener UseUtc()
{
this.UseUtcTime = true;
return this;
}
public DailyTraceListener UseHeader()
{
this.HasHeader = true;
return this;
}
protected virtual void WriteHeader()
{
this.LogFileWriter.WriteLine(string.Format("{0},{1},{2},{3},{4}",
"Time",
"Type",
"Source",
"ID",
"Message"));
}
protected virtual string FormatTime(DateTime time)
{
return time.ToString("o");
}
private DateTime GetCurrentTime()
{
if (this.UseUtcTime)
{
return DateTime.UtcNow;
}
else
{
return DateTime.Now;
}
}
private void InitializeLogFile()
{
this.CheckDisposed();
try
{
if (this.LogFileWriter != null)
{
this.LogFileWriter.Dispose();
}
if (this.LogFileStream != null)
{
this.LogFileWriter.Dispose();
}
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
var currentTime = this.GetCurrentTime();
var fileName = $"{currentTime.ToString("yyyy-MM-dd")}.log";
this.CurrentLogFilePath = Path.Combine(this.LogFolder, fileName);
// Ensure the folder is there
Directory.CreateDirectory(this.LogFolder);
// Create/Open log file
this.LogFileStream = new FileStream(this.CurrentLogFilePath, FileMode.Append);
this.LogFileWriter = new StreamWriter(this.LogFileStream);
// Write Header if needed
if (this.LogFileStream.Length == 0 && this.HasHeader)
{
this.WriteHeader();
}
}
private void CheckFile()
{
this.CheckDisposed();
var currentTime = this.GetCurrentTime();
if (this.CurrentLogDate == null || currentTime.Date != this.CurrentLogDate)
{
this.InitializeLogFile();
this.CurrentLogDate = currentTime.Date;
}
}
private void CheckDisposed()
{
if (this.Disposed)
{
throw new InvalidOperationException("The Trace Listener is Disposed.");
}
}
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
{
var time = this.FormatTime(this.GetCurrentTime());
this.WriteLine(string.Format("{0},{1},{2},{3},{4}",
time,
eventType,
EscapeCsv(source),
id.ToString(),
EscapeCsv(message)));
}
public override void Write(string message)
{
try
{
this.LogLocker.Wait();
this.CheckDisposed();
this.CheckFile();
var currentTime = this.GetCurrentTime();
this.LogFileWriter.Write(message);
this.LogFileWriter.Flush();
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
finally
{
this.LogLocker.Release();
}
}
public override void WriteLine(string message)
{
this.Write(message + Environment.NewLine);
}
protected string EscapeCsv(string input)
{
for (int i = 0; i < input.Length; i++)
{
if (input[i] == ',' || input[i] == '\n')
{
input = input.Replace("\"", "\"\"");
return $"\"{input}\"";
}
}
return input;
}
protected override void Dispose(bool disposing)
{
this.Disposed = true;
try
{
this.LogFileWriter?.Dispose();
this.LogFileStream?.Dispose();
this.LogLocker.Dispose();
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
base.Dispose(disposing);
}
}