C#使用txt文件记录log
功能如下:
1、程序运行时,在D盘创建一个名为X-RAY的文件夹,里面创建一个alarm log.txt和一个Run log.txt文件;
2、如果已经存在则不创建,同时读取文件中的内容;
3、如存在,在每个文件的末尾回车后,依次每行添加log内容;
4、log每行内容以“当前日期时间(精确到毫秒)---log内容”的格式进行写入记录;
当然,下面是用C#实现描述的功能,记录日志到文本文件:
```csharp
using System;
using System.IO;
public class LogService
{
private const string BasePath = "D:\\X-RAY";
private const string AlarmLogFileName = "alarm log.txt";
private const string RunLogFileName = "Run log.txt";
public void LogAlarm(string logContent)
{
LogToFile(AlarmLogFileName, logContent);
}
public void LogRun(string logContent)
{
LogToFile(RunLogFileName, logContent);
}
private void LogToFile(string fileName, string logContent)
{
string fullPath = Path.Combine(BasePath, fileName);
string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} --- {logContent}";
try
{
if (!Directory.Exists(BasePath))
{
Directory.CreateDirectory(BasePath);
}
using (StreamWriter sw = File.AppendText(fullPath))
{
sw.WriteLine(logEntry);
}
}
catch (Exception ex)
{
// 在这里处理潜在的异常
Console.WriteLine($"写入日志文件时出错: {ex.Message}");
}
}
}
public class Program
{
public static void Main()
{
LogService logger = new LogService();
logger.LogAlarm("发生了一些错误!");
logger.LogRun("应用程序已启动。");
// 测试一些额外的日志记录
for (int i = 0; i < 5; i++)
{
logger.LogRun($"记录日志 {i}.");
}
}
}
```
请确保包含必要的 `using` 指令,并运行 `Main()` 方法,以查看日志被记录在文本文件中。
请注意,这个示例代码是一个基本例子。在真实的应用程序中,你可能需要更优雅地处理异常,并根据你的特定用例实现其他功能,比如日志轮转、日志级别等。
带有详细注释的用C#实现记录日志到文本文件的代码:
```csharp
using System;
using System.IO;
public class LogService
{
private const string BasePath = "D:\\X-RAY"; // 设置基本路径,即D盘根目录下的X-RAY文件夹
private const string AlarmLogFileName = "alarm log.txt"; // 报警日志文件名
private const string RunLogFileName = "Run log.txt"; // 运行日志文件名
// 记录报警日志
public void LogAlarm(string logContent)
{
LogToFile(AlarmLogFileName, logContent);
}
// 记录运行日志
public void LogRun(string logContent)
{
LogToFile(RunLogFileName, logContent);
}
// 内部方法用于写入日志到指定文件
private void LogToFile(string fileName, string logContent)
{
string fullPath = Path.Combine(BasePath, fileName); // 获取完整的日志文件路径
string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} --- {logContent}"; // 构建日志行内容,包括日期时间和日志内容
try
{
if (!Directory.Exists(BasePath)) // 检查X-RAY文件夹是否存在,如果不存在则创建
{
Directory.CreateDirectory(BasePath);
}
// 使用StreamWriter打开文件,如果文件不存在则创建并追加内容
using (StreamWriter sw = File.AppendText(fullPath))
{
sw.WriteLine(logEntry); // 写入日志行
}
}
catch (Exception ex)
{
// 在这里处理潜在的异常,比如文件被占用、权限问题等
Console.WriteLine($"写入日志文件时出错: {ex.Message}");
}
}
}
public class Program
{
public static void Main()
{
LogService logger = new LogService();
// 记录报警日志
logger.LogAlarm("发生了一些错误!");
// 记录运行日志
logger.LogRun("应用程序已启动。");
// 测试一些额外的日志记录
for (int i = 0; i < 5; i++)
{
logger.LogRun($"记录日志 {i}.");
}
}
}
```