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);
    }
}
相关推荐
初级代码游戏7 小时前
C#:程序发布的大小控制 裁剪 压缩
c#·.net·dotnet·压缩·大小·发布·裁剪
量子物理学10 小时前
Modbus TCP
c#·modbus tcp
人工智能AI技术11 小时前
能用C#开发AI吗?
人工智能·c#
自己的九又四分之三站台14 小时前
6. 简单将原生代码改为流式请求
c#
一叶星殇16 小时前
C# .NET 如何解决跨域(CORS)
开发语言·前端·c#·.net
JQLvopkk17 小时前
C#调用Unity实现设备仿真开发浅述
开发语言·unity·c#
zxy284722530117 小时前
使用Topshelf部署window后台服务(C#)
c#·安装·topshelf·后台服务
缺点内向19 小时前
C# 高效统计 Word 文档字数:告别手动,拥抱自动化
c#·自动化·word
skywalk816320 小时前
介绍一下 Backtrader量化框架(C# 回测快)
开发语言·c#·量化
Never_Satisfied20 小时前
C#数组去重方法总结
开发语言·c#