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);
    }
}
相关推荐
椒颜皮皮虾྅4 小时前
OpenVINO C# API 3.3.1:支持OpenVINO 2026.3及GenAI增强
人工智能·c#·openvino
半亩码田7 小时前
C#转Python第3.1篇:Python 的 class 没有访问修饰符?面向对象的另一条路
开发语言·python·c#
唐青枫13 小时前
别再手写 args[0]:C#.NET CommandLineParser 命令行工具实战详解
c#·.net
LccKyI14 小时前
C#学习day06(方法/函数及其关键字,附思维导图)
经验分享·学习·c#
.Peter15 小时前
.NET/WPF 程序在部分 Windows 电脑无法保存用户环境变量:使用 DPAPI 实现安全兼容
windows·信息安全·c#·.net·wpf·环境变量·dpapi
农村小镇哥15 小时前
怎么把HTM格式转化成WORD
ui·c#·word
农村小镇哥15 小时前
C#读取CSV文件的方法
服务器·数据库·c#
FuckPatience16 小时前
C# 报错参数无效
c#
北域码匠1 天前
PID 控制算法完整详解(C# 原生实现,无第三方库)
c#·pid控制·工控开发·闭环控制·自动控制算法·数字pid·增量式pid
离陌在学C#1 天前
C# 重载与重写:深入理解面向对象编程的核心概念
java·c#