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);
    }
}
相关推荐
99乘法口诀万物皆可变2 小时前
CANdelaStudio类似页面制作方案
c#
ytttr8732 小时前
基于C#的CAN总线数据解析BMS上位机
android·unity·c#
在路上看风景2 小时前
1.10 线程其他操作
c#
步步为营DotNet3 小时前
深度解析C# 11的Required成员:编译期验证保障数据完整性
java·前端·c#
武藤一雄5 小时前
C# 语法糖详解
后端·microsoft·c#·.net
武藤一雄5 小时前
C#:进程/线程/多线程/AppDomain详解
后端·微软·c#·asp.net·.net·wpf·.netcore
曹牧6 小时前
在C#中,string和String
开发语言·c#
小菱形_7 小时前
【C#】LINQ
开发语言·c#·linq
曹牧8 小时前
C#:foreach
开发语言·c#