C# 实现日志记录功能

在winform开发过程中,有时候会需要日志功能记录软件运行情况。

本文主要介绍如何使用C#开发日记记录模块。

实现方案

整体思路就是调用日志功能方法。关于日志功能方法设计思路:

  • 确认日志文件格式和路径
  • 判断文件和路径是否存在,如果不存在,则创建对应的文件夹和文件
  • 使用using、streamwrite,将内容写入到文件中
    另外在本项目中,通过控件的事件调用日志记录功能

知识点

Path

对包含文件或目录路径信息的 String 实例执行操作

  • 方法
  • path.Combine
    将字符串合并到路径中。
csharp 复制代码
string filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs", "app_log.txt");

Directory

公开用于通过目录和子目录进行创建、移动和枚举的静态方法。 此类不能被继承

方法

  • Exists
csharp 复制代码
public static bool Exists (string? path);

path:测试的文件路径

返回:boolean

如果 path 指向现有目录,则为 true;如果该目录不存在或者在尝试确定指定目录是否存在时出错,则为 false。

  • CreateDirectory
    在指定路径中创建所有目录。
csharp 复制代码
public static System.IO.DirectoryInfo CreateDirectory (string path);

path:要创建的目录

返回:DirectoryInfo

一个表示在指定路径的目录的对象。 无论指定路径的目录是否已经存在,都将返回此对象。

Streamwriter

实现一个 TextWriter,用于以特定编码将字符写入流。

  • WriteLine
    WriteLine(String):将字符串写入流,后跟行终止符。

File

提供用于创建、复制、删除、移动和打开单个文件的静态方法,并有助于创建 FileStream 对象。

  • CreateText
    创建或打开用于写入 UTF-8 编码文本的文件。 如果文件已存在,则替换其内容。
csharp 复制代码
public static System.IO.StreamWriter CreateText (string path);

Path:要打开以进行写入的文件

返回:一个StreamWriter,使用UTF-8编码写入到指定的文件

  • AppendText
    创建一个 StreamWriter,它将 UTF-8 编码文本追加到现有文件或新文件(如果指定文件不存在)。
csharp 复制代码
public static System.IO.StreamWriter AppendText (string path);

Path:要向其中追加内容的文件的路径。

返回:StreamWriter,一个流写入器,它将 UTF-8 编码文本追加到指定文件或新文件。

三目运算符

csharp 复制代码
condition ? expression1 : expression2;

判断条件是否成立,如果成立则执行表达式1,否则执行表达式2。

在本项目中,判断文件是否存在,如果不存在,则创建文件,如果存在,则追加内容

csharp 复制代码
StreamWriter sw = File.Exists(filepath)? File.AppendText(filepath) : File.CreateText(filepath)

字符串拼接

csharp 复制代码
string logtype=string.Empty;
string s=string.Empty;
string content=string.Empty;
 content = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] [{logtype}]:[{s}]\r\n";

Type

在日志记录中,需要获取控件的类型。

  • 方法
    GetType()
    获取控件类型
csharp 复制代码
button2.GetType().Name

返回String。

关键代码

  • 日志记录功能
csharp 复制代码
public  class TraceLog
{
    public void writelog(string s,string logtype)
    {
        //判断是否文件是否存在,如果不存在,则创建文件
        //将信息和发生时间写入流中
        //关闭文件流对象

        string filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs", "app_log.txt");
        string content=string.Empty;
        try
        {
            // 确保目录存在
            string logDir = Path.GetDirectoryName(filepath);
            if (!Directory.Exists(logDir)) Directory.CreateDirectory(logDir);

            // using自动管理流的生命周期(退出using块自动释放)
            // File.AppendText:等价于 FileMode.Append + Encoding.UTF8
            using (StreamWriter sw = File.Exists(filepath)
                ? File.AppendText(filepath)
                : File.CreateText(filepath))
            {
                // 写入时间+信息
                //string content = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] 操作信息:用户执行了XXX操作\r\n";
                 content = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] [{logtype}]:[{s}]\r\n";
                sw.WriteLine(content);
            }
        }
        catch
        {
            MessageBox.Show($"日志写入失败:{content}","错误",MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
  • 主窗体代码
csharp 复制代码
TraceLog App_log=new TraceLog();
private void button1_Click(object sender, EventArgs e)
{
    string CtrType = GetType().Name + "-" + button1.GetType().Name;
    App_log.writelog(button1.Tag.ToString(), CtrType);
}

private void button2_Click(object sender, EventArgs e)
{
    string CtrType = GetType().Name + "-" + button2.GetType().Name;
    App_log.writelog(button2.Tag.ToString(), CtrType);
}

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyValue==13)
    {
        string CtrType = GetType().Name +"-"+ textBox1.GetType().Name;
        App_log.writelog(textBox1.Tag.ToString(), CtrType);
    }
}

private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 13)
    {
        string CtrType = GetType().Name+ "-" + textBox2.GetType().Name;
        App_log.writelog(textBox2.Tag.ToString(), CtrType);
    }
}
相关推荐
用户37215742613516 小时前
如何使用 C# 转换 PowerPoint 为 HTML:完整指南
c#
软泡芙17 小时前
【C# 】各种等待大全:从入门到精通
开发语言·c#·log4j
夏霞18 小时前
IIS 应用程序池 3 种标识:ApplicationPoolIdentity / LocalSystem / LocalService 权限区别(超清晰)
c#·.net
SteveDraw18 小时前
常见的设计模式及工业场景下应用(更新中)
设计模式·c#·编码规范·gof23
SunnyDays101118 小时前
如何使用 C# 转换 PowerPoint 为 HTML:完整指南
人工智能·opencv·计算机视觉·c#
weixin_520649871 天前
WinForm数据展示组件ListView
c#
程序设计实验室1 天前
Spark.NET:一个试图把 Django / Rails 式开发体验带回 .NET 世界的全栈 Web 框架。
c#
byoass1 天前
智巢AI知识库深度解析:企业文档管理从大海捞针到精准狙击的进化之路
开发语言·网络·人工智能·安全·c#·云计算
njsgcs2 天前
solidworks自动标注折弯4 无向图 c#
开发语言·c#·solidworks
我是唐青枫2 天前
C#.NET ThreadLocal 深入解析:线程独享数据、性能收益与实战边界
c#·.net