前言
很多时候,我们的系统都需要做日志功能,包括系统异常报错、非法访问等等都想要进行记录和统计,这样的数据数量会很多却又跟具体的业务没有太大关系,所以一般情况下可能会选择以txt文本文件的形式保存系统日志。
下面我将以C#的控制台应用程序的形式实现一个简单的Txt文本文件保存系统日志的功能。
功能需求分析
- 一天的日志一个txt文本文件,文本文件中每行为一条日志,以日期命名日志文件
- 一个月的日志文件一个文件夹,并以年月命名文件夹
- 自动创建文件夹及文件,执行日志添加操作之前先检测文件夹或文件是否存在
具体实现
程序运行,提示用户输入日志信息及日志日期,而后程序将进行日志创建操作,执行一条日志后提示用户输入其他键继续,输入[ESC]键退出程序。
Visual Studio 2019创建控制台应用程序,在Program.cs文件中键入如下程序,执行即可。
using System;
using System.IO;
namespace TextfilelogDemo
{
class Program
{
static void Main(string[] args)
{
do
{
Console.Write("\n请输入日志信息:");
string logMSG = Console.ReadLine();
Console.Write("请输入日志保存日期(eg:2021-05-16 12:35):");
string logTimestr = Console.ReadLine();
DateTime logTime = new DateTime();
while (!DateTime.TryParse(logTimestr, out logTime))
{
Console.Write("日期输入出错,请重新输入:");
logTimestr = Console.ReadLine();
}
logTime = Convert.ToDateTime(logTimestr);
string path = @"D:\LogDemo\";
logMSG = Guid.NewGuid().ToString() + " " + DateTime.Now.ToString("G") + " " + logMSG;
action(logMSG, logTime, path);
Console.WriteLine("按任意键继续,按ESC键结束程序。");
} while (Console.ReadKey().Key != ConsoleKey.Escape);
}
private static void action(string logMSG, DateTime logTime, string path)
{
string dirPath = path + logTime.ToString("Y");
if (!Directory.Exists(dirPath))
{
DirectoryInfo directoryInfo = new DirectoryInfo(dirPath);
directoryInfo.Create();
}
string logFileName = dirPath + "\\" + logTime.ToString("D") + ".txt";
if (!File.Exists(logFileName))
{
FileStream fileStream = File.Create(logFileName);
fileStream.Close();
}
FileStream fileRead = new(logFileName, FileMode.Append, FileAccess.Write, FileShare.Write);
StreamWriter streamWriter = new StreamWriter(fileRead, System.Text.Encoding.Default);
streamWriter.WriteLine(logMSG);
streamWriter.Flush();
streamWriter.Close();
fileRead.Close();
}
}
}
献上源码 欢迎Star
Github源码链接: Github-TextfilelogDemo.
Gitee源码链接: Gitee-TextfilelogDemo.